Concise scheme R5RS define struct or class with multiple fields

368 views Asked by At

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?

1

There are 1 answers

0
C. K. Young On BEST ANSWER

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))