简体   繁体   中英

Concise scheme R5RS define struct or class with multiple fields

I've managed to define a struct with one field, how to define multiple fields in one struct or class?

I'm new to R5RS, I can only come up with problematic code, please see it as pseudo code expressing what I'm trying to do.

(define recipe 
    (let (salt 5)
         (sauce "ketchup")))

or

(define recipe
   '((let salt 5)
     (let sauce "ketchup")))

What's the most concise and common way(s) to do this?

Most Scheme implementations provide records via SRFI 9 . So in your case, you can define a recipe record type like so:

(define-record-type <recipe>
  (recipe salt sauce)
  recipe?
  (salt recipe-salt)
  (sauce recipe-sauce))

Then you can use it like this:

> (define salty-ketchup (recipe 5 "ketchup"))
> (recipe-salt salty-ketchup)
5
> (recipe-sauce salty-ketchup)
"ketchup"

If you're using Racket, there's an even simpler syntax for defining structs.

(struct recipe (salt sauce))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM