Macro to use dot.notation to get structure fields in Racket

纵然是瞬间 提交于 2019-12-22 10:53:19

问题


For a structure and its instance defined as follows:

(struct dog (name breed age))  
(define mydog (dog "lassie" "collie" 5))

(example from https://learnxinyminutes.com/docs/racket/)

The usual way to get a structure field is as follows:

(dog-name mydog) ; => "lassie"

Can there be a macro so that we can perform above using following dot notation:

(mydog.name) ; => "lassie" 

Or, parentheses may not be needed:

mydog.name ; => "lassie" 

Macro for dot notation is used on this page: http://www.greghendershott.com/fear-of-macros/pattern-matching.html#%28part._hash..refs%29 but I am not able to use it for above purpose. I also saw some details of structure macro on this page: Is struct a macro in Racket?

Edit: as suggested in comments and as mentioned on https://docs.racket-lang.org/reference/reader.html?q=read-cdot#%28part._parse-cdot%29, I tried read-cdot, but it does not work:

#lang racket
(read-cdot #t) 
(struct dog (name breed age))  
(define mydog (dog "lassie" "collie" 5))
(dog-name mydog) ; works
mydog.dog-name   ; does not work; 

The error is:

 mydog.dog-name: unbound identifier in module in: mydog.dog-name

来源:https://stackoverflow.com/questions/39145000/macro-to-use-dot-notation-to-get-structure-fields-in-racket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!