2

我正在尝试制作该功能

author-book

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

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

我试过了

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

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

4

3 回答 3

2

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

(define (author-of-book b)
    (cond 
        [(audiobook? b) (audiobook-author b)]
        [(hardcover? b) (hardcover-author b)]
        [(ebook? b)     (ebook-author b)]))

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

于 2013-02-05T04:12:14.697 回答
2

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

(define (author-of-book b)
  ((cond [(audiobook? b) audiobook-author]
         [(hardcover? b) hardcover-author]
         [(ebook? b)     ebook-author])
   b))

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

(author-of-book audiobook1)
=> "Suzanne Collins"

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

(author-of-book hardcover1)
=> "Jud White"
于 2013-02-05T04:37:15.990 回答
1

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

(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来访问三种书籍中任何一种的作者字段。

> (book-author audiobook1)
"Suzanne Collins"
> (book-author ebook1)
"Veronica Roth"
> (book-author hardcover1)
"Jud White"
于 2013-02-06T00:26:30.563 回答