What are map, filter, and fold?#
map#
map takes a function and a list, and applies the function to each element in the list, returning the resulting list.
Type signature of map in Haskell
map :: (a -> b) -> [a] -> [b]
Racket code
(define (mymap function mylist)
(cond
((null? mylist) '())
(else (cons (function (car mylist)) (mymap function (cdr mylist)) ))
)
)
(define (add2 x) (+ 2 x))
(mymap add2 '(1 2 3 4 5 6 7 8))
=> (3 4 5 6 7 8 9 10)
filter#
As the name suggests, filter extracts the values from a list that satisfy a given condition.
Type signature of filter in Haskell
filter :: (a -> Bool) -> [a] -> [a]
Racket code
(define (myfilter condition? mylist)
(cond
((null? mylist) '())
((condition? (car mylist)) (cons (car mylist) (myfilter condition? (cdr mylist))))
(else (myfilter condition? (cdr mylist)))
)
)
(define (odd? a)
(eq? (modulo a 2) 1)
)
(myfilter odd? '(-1 -2 -3 -4 -5 -6 -7 -8 -9 -10))
=> (-1 -3 -5 -7 -9)
fold#
Fold represents the concept of folding or reducing a list. Generally, it can be divided into left fold and right fold.
Let's take left fold (foldl) as an example.
Type signature of foldl in Haskell
foldl :: (a -> b -> a) -> a -> [b] -> a
Racket code
(define (myfoldl base function mylist)
(cond
((null? mylist) base)
(else (myfoldl (function base (car mylist)) function (cdr mylist)))
)
)
(define (add x y)
(+ x y)
)
(myfoldl 0 add '(1 2 3 4 5 6 7 8 9))
=> 45