BBladem83
BBladem83

Reputation: 623

Scheme (DrRacket) - Combining Two Higher-Order Functions with Lambda in Defintion

For reference I am programming with Scheme using DrRacket.

I am trying to code the definition daily-to that 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.

From my understanding this definition needs to use both filter and map, along with lambda, as this is a problem about higher order functions and lambda. I do not appear to be doing this correctly although.

Hoping I can get assistance on my daily-to definition, as it is not running correctly.

Here is my program:

(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)))

Thank you in advance!

Upvotes: 0

Views: 267

Answers (1)

C. K. Young
C. K. Young

Reputation: 223173

Here's a definition of daily-to that seems to make sense off the top of my head. It is not tested.

(define (daily-to city alof)
  (map flight-to
       (filter (lambda (flight)
                 (and (string=? city (flight-from flight))
                      (string=? "daily" (flight-frequency flight))))
               alof)))

Upvotes: 1

Related Questions