【问题标题】:Creating a dictionary in racket在球拍中创建字典
【发布时间】:2020-02-12 10:53:10
【问题描述】:

编写函数 build-author-index 使用 a(listof Book) 和唯一作者列表(字符串)。该函数生成一个 AuthorIndex,其中键是所使用的作者(以相同的顺序),值是该作者在 Book 列表中的所有书籍的标题(也以相同的顺序)。

以下是我的代码。我必须使用带有列表缩写的初学者。我只允许使用 cons, first, second, third, rest, empty?, eq?缺点?、列表、成员?和长度。

由于堆栈溢出不允许我发布我的代码图像

【问题讨论】:

  • Stack Overflow 有 {} 来格式化文本。当 (first a b c d) 最初只接受一个参数时,你认为它应该做什么? (其他在author-index-list(author-index-list '() my-bookshelf) ; ==> my-bookshelf 可以吗?

标签: list if-statement recursion racket cons


【解决方案1】:
#lang racket

(define my-bookshelf
  '((book-name-1 author-1)
    (book-name-2 author-2)
    (book-name-3 author-3)
    (book-name-4 author-4)
    (book-name-5 author-5)))


(define (bookname-of-given-author bookshelf author)
  (cond
    [(empty? bookshelf)
     (error "no this author")]
    [(equal? author (second (first bookshelf)))
     (first (first bookshelf))]
    [else
     (bookname-of-given-author (rest bookshelf) author)]))


;;; Test
(bookname-of-given-author my-bookshelf 'author-1)
(bookname-of-given-author my-bookshelf 'author-4)


(define (build-author-index bookshelf author-ls)
  (cond
    [(empty? author-ls) empty]
    [else
     (cons (bookname-of-given-author my-bookshelf (first author-ls))
           (build-author-index (rest bookshelf) (rest author-ls)))]))


;;; Test
(build-author-index my-bookshelf '(author-1 author-4))
(build-author-index my-bookshelf '(author-4 author-3 author-2 author-1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2015-04-08
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多