wtfunctional/examples/01_haskell.hs

40 lines
919 B
Haskell
Raw Permalink Normal View History

extract :: [a] -> a
extract [] = error("Too few objects")
extract (x:xs) = x
a = extract [1,2,3,4,5]
-- a == 1
-- better use fst
addto :: (Num a) => [a] -> a -> [a]
addto [] _ = [] -- edge case (list empty)
addto (x:xs) y = (x+y) : addto xs y
b = [1..4]
c = addto b 4
-- c == [5,6,7,8]
-- better use c = map (+4) b
-- d == [25,36,49,64]
d = map (^2) c
e = filter (\x -> (mod x 2) == 0) c
-- e == [6,8]
mfold :: (t -> t1 -> t1) -> t1 -> [t] -> t1
mfold f z [] = z
mfold f z (x:xs) = f x (mfold f z xs)
msum = mfold (+) 0
g = msum [1..100]
-- use sum [1..100] instead, and use right folds
pt = [(a,b,c) | a <- [1..15], b <- [1..a], c <- [1..b], a^2 == b^2 + c^2]
bsort :: (t -> t -> Bool) -> [t] -> [t]
bsort f [] = []
bsort f (x:xs) = (bsort f a) ++ [x] ++ (bsort f b)
where a = [ y | y <- xs, not (f x y) ]
b = [ y | y <- xs, (f x y) ]
mbsort = bsort (\x y -> (x < y))
h = [1, 20, -10, 5]
i = mbsort h