关于 scheme:functions 结构定义

functions structure definitions

我正在尝试制作函数

author-book

给定一本书,产生这本书的作者。这是我为此创建的数据-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(define-struct audiobook ( title author length-in-minutes voice-person))

(define-struct ebook ( title author size-in-kolobytes symbol ))

(define-struct hardcover (title author number-of-pages genre ))

(define audiobook1 (make-audiobook"The Hunger Games""Suzanne Collins""50 minutes""David Larrson"))
(define audiobook2 (make-audiobook"Catching Fire""Suzanne Collins""55 minutes""David Larrson"))
(define audiobook3 (make-audiobook"Mockingjay""Suzanne Collins""40 minutes""David Larrson"))

(define ebook1 (make-ebook"Divergent""Veronica Roth""100000kbs" 'Kindle))
(define ebook2 (make-ebook"Dracula""Bram Stocker""134000kbs" 'Ebook))
(define ebook3 (make-ebook"Jane Eyre""Charlotte Bront?""400000kbs" 'IPad))

(define hardcover1 (make-hardcover"Pursued""Jud White""100000kbs""Crime"))
(define hardcover2 (make-hardcover"Private Berlin""James Patterson""100000kbs""Suspense"))
(define hardcover3 (make-hardcover"Francona""Terry Francona""100000kbs""Sports"))

我试过了

1
2
(define (author-of-book n)
        (audiobook-author n))

这给了我只有有声读物的作者。有没有办法让我不用编写三个单独的函数就可以得到其余部分的作者? (如电子书作者...)


这是另一种可能的实现,只是比@jozefg 的答案短一点(经过测试和工作):

1
2
3
4
5
(define (author-of-book b)
  ((cond [(audiobook? b) audiobook-author]
         [(hardcover? b) hardcover-author]
         [(ebook? b)     ebook-author])
   b))

cond 表达式返回在每种情况下使用的正确过程,并且被选中的过程应用于 b。例如:

1
2
3
4
5
6
7
8
(author-of-book audiobook1)
=>"Suzanne Collins"

(author-of-book ebook1)
=>"Veronica Roth"

(author-of-book hardcover1)
=>"Jud White"


你可以很容易地检查它是什么类型的书,然后从那里开始

1
2
3
4
5
(define (author-of-book b)
    (cond
        [(audiobook? b) (audiobook-author b)]
        [(hardcover? b) (hardcover-author b)]
        [(ebook? b)     (ebook-author b)]))

这有点冗长,但也没什么不好。


你有三个不同的结构,它们共享一个共同的子结构:三个都有一个 titleauthor。您可以在结构定义中对此共享进行编码:

1
2
3
4
5
(define-struct book (title author))

(define-struct (audiobook book) (length-in-minutes voice-person))
(define-struct (ebook book) (size-in-kolobytes symbol))
(define-struct (hardcover book) (number-of-pages genre))

我们已经清理了三种结构中的字段重复,作为额外的奖励,我们可以简单地使用 book-author 访问三种书籍中任何一种的作者字段。

1
2
3
4
5
6
> (book-author audiobook1)
"Suzanne Collins"
> (book-author ebook1)
"Veronica Roth"
> (book-author hardcover1)
"Jud White"