Let's use macros to solve the problem.
In my last post, I relied on the build-in 'call' function to access the properties of static objects. Let's create a wrapper to 'call' that lets us access the properties of dicts in exactly the same manner as we do properties of other objects:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defmacro dot | |
((obj prop . tl) | |
`(let ((obj ,obj)) | |
(case (element 1 obj) | |
('dict | |
,(case tl | |
(() | |
`(case (: dict find ,prop obj) | |
('error 'undefined) | |
((tuple 'ok valx) valx))) | |
(_ `(: dict store ,prop ,(hd tl) obj)))) | |
(_ (call obj ,prop ,@tl)))))) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defun test () | |
(let* ((dog1 (: dog new)) | |
(dog2 (: dict new)) | |
(dog1_2 (dot dog1 'name 'lola)) | |
(dog2_2 (dot dog2 'name 'rocky))) | |
(list (dot dog1_2 'name) | |
(dot dog2_2 'name)))) |
> (: dog test)
(lola rocky)
I think this is kinda of cool, though to be honest I'm not entirely sure it's a great idea to obfuscate in the code whether we're dealing with dicts or static objects.
2 comments:
A bit off topic, but have you given thought to using disqus for this blog? Anyway, I enjoy reading your blog. Keep up the good work.
Found this by accident; what you call obfuscation might some call rather generalization and promote it as a new trend of generalized objects. Anyway I guess I'm rather on your side and would assume it a bit too "hacky"...
Post a Comment