even 1
False
even 2
True
map even [1,2,3,4,5]
[False,True,False,True,False]
filter even [1,2,3,4,5]
[2,4]
even
is a first-order function.
map
and filter
are higher-order functions.
map :: (a -> b) -> [a] -> [b] filter :: (a -> Bool) -> [a] -> [a]
filter even [1..5] == [2,4]
squares = map square [1..5] where square x = x*x
take 2 "Haskell"
"Ha"
map (take 2) ["Hello","Haskell"]
["He","Ha"]
5*3 == 15
(*3) 5 == 15
map (*3) [1..5] == [3,6,9,12,15]
filter (<3) [1..5] == [1,2]
filter (3<) [1..5] == [4,5]
removeSpaces "abc def \n ghi" = "abcdefghi"
isSpace
from module Data.Char
,
removeSpaces s = filter (not . isSpace) s
(f . g) x = f (g x)
(b->c) -> (a->b) -> (a->c)
--square x = x*x
square = \ x -> x*x
squares = map square numbers where square x = x*x numbers = [1..5]
squares = map (\x -> x*x) [1..5]
Int -> Int -> Int
Int -> (Int -> Int)
(Int -> Int) -> Int
Int -> Int -> Int
Int -> (Int -> Int)
(b->c)->(a->b)->(a->c)
(b->c)->(a->b)-> a->c
Int -> Int -> Int
(Int,Int) -> Int
Int
Int
curry
uncurry
|
|
map :: (a -> b) -> [a] -> [b] map f [] = [] map f (x:xs) = f x:map f xs
filter :: (a -> Bool) -> [a] -> [a] filter p [] = [] filter p (x:xs) | p x = x:filter p xs | otherwise = filter p xs
sum [] = 0
sum (x:xs) = x + sum xs
product [] = 1
product (x:xs) = x * product xs
foldr op base [] = base foldr op base (x:xs) = x `op` foldr op base xs
x `f` y
f x y
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr
is also known as reduce.
You already know map
, so now you know
the essence of
MapReduce!
sum xs = foldr (+) 0 xs product xs = foldr (*) 1 xs
foldr
is useful in many more cases!
or xs = foldr (||) False xs and xs = foldr (&&) True xs concat xs = foldr (++) [] xs maximum (x:xs) = foldr max x xs
foldr (&) z
&
:
&
[]
z
xs == a : b : c : d : … : []
foldr (&) z xs == a & b & c & d & … & z
foldr (+) 0 xs == a + b + c + d + … + 0
foldr (*) 1 xs == a * b * c * d * … * 1
f1 xs = foldr (:) [] xs
f2 xs ys = foldr (:) ys xs
f3 xs = foldr snoc [] xs where snoc x ys = ys++[x]
f4 f xs = foldr fc [] xs where fc x ys = f x:ys
unlines ["abc","def","ghi"] = "abc\ndef\nghi\n"
unlines ls = foldr (\xs ys->xs++"\n"++ys) [] ls
unlines ls = foldr join [] ls
where join xs ys = xs ++ "\n" ++ ys
f x = g x
f = g
or = foldr (||) False
and = foldr (&&) True
concat = foldr (++) []
removeSpaces = filter (not . isSpace)
unlines = foldr (\xs ys->xs++"\n"++ys) []
takeLine :: String -> String
takeLine "abc\ndef\nghi\n" = "abc"
takeWhile :: (a->Bool) -> [a] -> [a]
dropWhile :: (a->Bool) -> [a] -> [a]
lines :: String -> [String]
lines "abc\ndef\nghi\n" = ["abc","def","ghi"]
segments :: (a->Bool) -> [a] -> [[a]]
words :: String -> [String]
words "abc def ghi" = ["abc","def","ghi"]
wordCounts :: String -> String
putStr (wordCounts "hello clouds\nhello sky")
clouds: 1
hello: 2
sky: 1
sort :: Ord a => [a] -> [a] sortBy :: (a->a->Ordering) -> [a] -> [a]
pick 1 = fst pick 2 = snd
id :: a -> a