scheme struct

Beautiful Racket: Importing & exporting

struc­ture type is a user-defined data struc­ture with an arbi­trary number of fields. Like a hash table, a struc­ture type allows access to its fields by name. Like a vector, the number of fields is fixed by the struc­ture-type defi­n­i­tion.

The struct form defines the struc­ture type itself, and also manu­fac­tures a pred­i­cate, plus getters (and, for mutable struc­ture types, setters) for each field. The #:transparent option makes the struc­ture type print­able in the REPL:

(struct style (color size weight) #:transparent #:mutable)
(define s (style "red" 42 'bold))
s ; (style "red" 42 'bold)
(style? s) ; #t
(style-color s) ; "red"
(set-style-color! s "blue")
(style-color s) ; "blue"

(struct style (color size weight) #:transparent #:mutable)
(define s (style "red" 42 'bold))
s ; (style "red" 42 'bold)
(style? s) ; #t
(style-color s) ; "red"
(set-style-color! s "blue")
(style-color s) ; "blue"

It’s not uncommon for a Rack­e­teer to throw some values into a list as a quick-and-dirty data struc­ture. But for anything that will be used more than once, a struc­ture type is better:

  1. The getters and setters have read­able names.

  2. The struc­ture type can have fields added to its defi­n­i­tion without changing existing refer­ences.

  3. An instance of a struc­ture type is repre­sented as a single object in memory, so it can be passed around a program “by refer­ence” (meaning, it’s not dupli­cated if passed from one func­tion to another).

  4. A struc­ture type has its own unique pred­i­cate, which can be effi­ciently tested (say, inside a contract).

The disad­van­tage of a struc­ture type is that it’s a distinct data type from a hash table, vector, or list, so it can’t be directly used with library func­tions that consume those types. There’s a little more house­keeping to get values in & out.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值