【发布时间】:2019-11-17 11:00:23
【问题描述】:
有人可以告诉我如何解决这个问题/给我一个模板吗?我不允许使用 map 或 lambda 或任何其他高级内置函数,只能列出
【问题讨论】:
标签: racket
有人可以告诉我如何解决这个问题/给我一个模板吗?我不允许使用 map 或 lambda 或任何其他高级内置函数,只能列出
【问题讨论】:
标签: racket
首先提取与输入字符串关联的国家:
(define (get-country l s)
(cond [(empty? (rest l)) (second (second (first l)))]
[else (if (equal? s (first (first l)))
(second (second (first l)))
(get-country (rest l) s))]))
然后提取与该国家/地区相关联的所有字符串:
(define (get-countries l s)
(cond [(empty? l) '()]
[else (if (equal? s (second (second (first l))))
(cons (first (first l)) (get-countries (rest l) s))
(get-countries (rest l) s))]))
然后把它们放在一起:
(define (same-country l s)
(get-countries l (get-country l s)))
当我们评估时,我们得到的结果与(list "YUL" "YVR" "YWG" "YYZ") 不同:
> (same-country alist "YUL")
(list "YYZ" "YWG" "YUL" "YVR")
所以我们检查结果是否是所需列表的排列。首先我们制作is-permutation:
(define (is-permutation l1 l2)
(and (not (and (cons? l1) (empty? l2)))
(not (and (empty? l1) (cons? l2)))
(or (and (empty? l1) (empty? l2))
(and (is-member (first l1) l2)
(is-permutation (rest l1)
(remove-one (first l1) l2))))))
(define (is-member e l)
(and (not (empty? l))
(or (equal? (first l) e)
(is-member e (rest l)))))
(define (remove-one e nel)
(cond [(empty? (rest nel)) '()]
[else (if (equal? (first nel) e)
(rest nel)
(cons (first nel) (remove-one e (rest nel))))]))
然后我们可以测试:
> (is-permutation (same-country alist "YUL")
(list "YUL" "YVR" "YWG" "YYZ"))
#true
【讨论】:
insert 中使用>= 以降序排列数字,您使用@987654332 @ 以升序排列字符串