功能结构定义

时间:2013-02-05 03:43:21

标签: scheme racket

我正在尝试制作这个功能

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

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

3 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分: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"

答案 2 :(得分:1)

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

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