有人可以告诉我如何解决此问题/给我一个模板吗?我不允许使用map或lambda或任何其他高级内置函数,只能使用列表
答案 0 :(得分:0)
首先提取与输入字符串关联的国家/地区:
(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