;; What does this evaluate to, and why?
(foldr - 0 (list 1 2 4 8 7 10))
;; foldr using op and base will turn
;; (cons a (cons b (cons c (cons d (cons e empty)))))
;; into
;; (op a (op b (op c (op d (op e base )))))
;; fold-r : [Y X -> X] X [Listof Y] -> X
(define (fold-r op base xs)
(cond [(empty? xs) base]
[else (op (first xs)
(fold-r op base (rest xs)))]))
;; add-10 : Number -> Number
(define (add-10 n)
(+ 10 n))
(define (add-10-to-all lon)
(map add-10 lon))
;; map using op will turn
;; (list a b c d e)
;; into
;; (list (op a) (op b) (op c) (op d) (op e))
;; my-map : [X -> Y] [Listof X] -> [Listof Y]
(define (my-map op xs)
(cond [(empty? xs) empty]
[else (cons (op (first xs))
(my-map op (rest xs)))]))
(define (add-x-to-all x lon)
;; add-x : Number -> Number
(local ((define (add-x n) (+ x n)))
(map add-x lon)))
#;(local ((define (add-x n) (+ 5 n)))
(map add-x (list 10 20 30)))
(check-expect (my-filter even? (list 3 1 4 1 5 9 2 6)) (list 4 2 6))
(check-expect (my-filter odd? (list 2 7 1 8 2 8)) (list 7 1))
;; my-filter : [X -> Boolean] [Listof X] -> [Listof X]
(define (my-filter test xs)
(cond [(empty? xs) empty]
[(test (first xs)) (cons (first xs) (my-filter test (rest xs)))]
[else (my-filter test (rest xs))]))
;; Returns true if the test is true for all items in the list
(define (all-true test xs)
(cond [(empty? xs) true]
[else (and (test (first xs)) (all-true test (rest xs)))]))
(define (all-true2 test xs)
(local ((define (my-and x y) (and x y)))
(foldr my-and true (map test xs))))
;; actually called andmap
;; Returns true if the test is true for any item in the list
(define (any-true test xs)
(cond [(empty? xs) false]
[else (or (test (first xs)) (any-true test (rest xs)))]))
;; actually called ormap
;; foldr, map, filter, andmap, ormap
;; Paint: [Listof Posn] Image -> draw a star at each posn on to the image
;; The sum of a list of random numbers in a given range
(foldr + 0 (map random (list ...a bunch of numbers...)))
;; Implementing map in terms of foldr
;; First, let's use foldr to tear apart a list...and put it right back together
(define (identity xs)
(foldr cons empty xs))
;; Following the pattern of what foldr does above, if we replace empty with empty,
;; and cons with cons, we'll just get our list back!
;; The only difference between the identity function and map is that before it puts
;; the list back together, it applies op to each item
(define (my-map2 op xs)
(local ((define (cons-op x ys)
(cons (op x) ys)))
(foldr cons-op empty xs)))