DrRacket-使用lambda产生具有相同元素的列表

时间:2019-11-17 03:03:58

标签: racket

我是球拍的新手,最近开始学习摘要列表功能。 我必须编写一个使用机场列表(same-country airports code)的函数airports和一个代表机场的三个字母的代码。该函数产生与给定机场具有相同国家/地区的所有机场代码的列表,并按字母升序排序。 如果代码不在关联列表中,则该函数将产生空白。

例如:

(define alist (list (list "YYZ" (list "Toronto" "Canada"))
                    (list "YWG" (list "Winnipeg" "Canada"))
                    (list "BGO" (list "Bergen" "Norway"))
                    (list "TRF" (list "Sandefjord" "Norway"))
                    (list "YUL" (list "Montreal" "Canada"))
                    (list "LHR" (list "London" "England"))
                    (list "YVR" (list "Vancouver" "Canada"))))

然后

(same-country alist "YUL") => (list "YUL" "YVR" "YWG" "YYZ")

有人可以告诉我如何解决此问题/给我一个模板吗?在这个问题中,我不允许使用任何命名的辅助函数,只有lambda ...我知道在使用显式递归时如何做,但是我对抽象列表函数的理解不够充分

1 个答案:

答案 0 :(得分:0)

版本3

; please tell us which language you use (in front of code)
; please take effort before adding comment
; language:intermediate student with lambda
(define same-country-v2
  (λ (airport-ls airport-name)
    ((λ (ls name1 name2)
       ; result
       (sort
        (map (λ (p) (first p))
             (filter (λ (x)
                       (or (equal? name1 (first (second x)))
                           (equal? name2 (second (second x)))))
                     ls))
        string<=?))
     airport-ls
     ; city name
     (first ((λ (airports airport-name) (second (first (filter (λ (x) (equal? (first x) airport-name)) airports)))) airport-ls airport-name))
     (second ((λ (airports airport-name) (second (first (filter (λ (x) (equal? (first x) airport-name)) airports)))) airport-ls airport-name)))))

;;; TEST
(same-country-v2 airports "YUL")
(same-country-v2 airports "BGO")