Map Examples
8.14

Map Examples🔗

  #lang typed/racket
   
  (require typed/rackunit)
   
  ;; given a number and a list of numbers, return the result
  ;; of multiplying every number in the list by the given number:
   
  ;; First, let's try with the design recipe:
   
  (define (mm-1 [num : Real] [lon : (Listof Real)]) : (Listof Real)
    (match lon
      ['() '()]
      [(cons f r) (cons (* num f) (mm-1 num r))]))
   
  ;; Next, let's use `map` for this, defining a function to use
  ;; with map, inside of the function:
   
  (define (mm-2 [num : Real] [lon : (Listof Real)]) : (Listof Real)
    (define (my-mult [b : Real])
      (* num b))
    (map my-mult lon))
   
  ;; Is there a way to abbreviate this? I don't really want to give `my-mult` a name.
  ;; yes!
   
  (define (mm-3 [num : Real] [lon : (Listof Real)]) : (Listof Real)
    (map (λ ([b : Real]) : Real (* num b)) lon))
   
  ;; that seems long. Can I omit some of the types on the unnamed function?
  ;; yes, the return type of this function can be inferred. That's a bit shorter:
   
  (define (mm-4 [num : Real] [lon : (Listof Real)]) : (Listof Real)
    (map (λ ([b : Real]) (* num b)) lon))
   
  ;; Is there another form that I could use for this?
  ;; Yes: in this case, a `for/list` would work fine:
   
  (define (mm-5 [num : Real] [lon : (Listof Real)]) : (Listof Real)
    (for/list ([b lon])
      (* num b)))
   
  ;; Hey! I tried the for/list in my situation, and TR was unable to
  ;; infer the type of `b`. Can I specify it manually?
  ;; Yes:
   
  (define (mm-6 [num : Real] [lon : (Listof Real)]) : (Listof Real)
    (for/list ([b : Real lon])
      (* num b)))
   
  (check-equal? (mm-1 100 '(3 4 5)) '(300 400 500))
  (check-equal? (mm-2 100 '(3 4 5)) '(300 400 500))
  (check-equal? (mm-3 100 '(3 4 5)) '(300 400 500))
  (check-equal? (mm-4 100 '(3 4 5)) '(300 400 500))
  (check-equal? (mm-5 100 '(3 4 5)) '(300 400 500))
  (check-equal? (mm-6 100 '(3 4 5)) '(300 400 500))