作为参考,我使用Scheme
编译DrRacket
。
我正在尝试对使用城市名称和航班列表的定义daily-to
进行编码,并返回航空公司每天从指定城市起飞的城市(字符串)列表。
根据我的理解,此定义需要同时使用filter
和map
以及lambda
,因为这是higher order functions
和lambda
的问题。我似乎没有正确地做到这一点。
希望我可以获得daily-to
定义的帮助,因为它运行不正确。
这是我的计划:
(define-struct flight (from to frequency))
;; Example: (make-flight "Boston" "Chicago" “daily”))
;; The frequency is one of “daily”, “weekday” or “weekend”.
(define myflights
(list
(make-flight "Boston" "Chicago" "daily")
(make-flight "New York" "Providence" "weekend")
(make-flight "Paris" "Moscow" "weekday")))
;; Signature: service-between?: String String ListOfFlights -> Boolean
;; Purpose: consumes two city names and a list of flights and determines
;; whether (true or false) there is a flight from the first city to the second.
;; Tests:
(check-expect (service-between? "Boston" "Chicago" myflights) true)
(check-expect (service-between? "New York" "Providence" myflights) true)
(check-expect (service-between? "Paris" "Moscow" myflights) true)
(check-expect (service-between? "Boston" "Providence" myflights) false)
;; Definition: service-between?
(define (service-between? city1 city2 alof)
(ormap
(lambda (str)
(and (string=? city1 (flight-from str))
(string=? city2 (flight-to str)))) alof))
;; Signature: daily-to: String ListOfFlights -> ListOfString
;; Purpose: consumes a city name and a list of flights and returns a list
;; of cities (strings) to which the airline has a daily flight from the given city.
;; Tests:
(check-expect (daily-to "Boston" myflights) (list "Chicago"))
(check-expect (daily-to "New York" myflights) empty)
(check-expect (daily-to "Paris" myflights) empty)
;; Definition: daily-to
(define (daily-to city alof)
(filter (map
(lambda (str)
(cond
[(and (string=? city (flight-from str)) (string=? "daily" (flight-frequency str))) (flight-to str)]
[else empty])) alof)))
提前谢谢!
答案 0 :(得分:1)
这里有一个daily-to
的定义,似乎有点理解。它没有经过测试。
(define (daily-to city alof)
(map flight-to
(filter (lambda (flight)
(and (string=? city (flight-from flight))
(string=? "daily" (flight-frequency flight))))
alof)))