0%

Programming in Haskell Chapter4 Exercises Solutions

Programming in Haskell是一本入门Haskell的好书,介绍页面以及配套的slides, vedios, codes都在这里


定义 halve

1
2
halve :: [a] -> ([a], [a])
halve a = let n = (length a) `div` 2 in (take n a, drop n a)

用三种方式定义safetail

1
2
3
4
5
6
7
8
9
10
11
12
13
14
-- conditional expression
safetail1 :: [a] -> [a]
safetail1 xs = if null xs then xs else tail xs

-- guarded equations
safetail2 :: [a] -> [a]
safetail2 xs | null xs = xs
| otherwise = tail xs

-- pattern matching
safetail3 :: [a] -> [a]
safetail3 [] = []
safetail3 (_:xs) = xs

定义并运算(disjunction operator)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-- 1 all pattern matching
md1 :: Bool -> Bool -> Bool
md1 True True = True
md1 True False = True
md1 False True = True
md1 False False = False

-- 2 wildcard pattern

md2 False False = False
md2 _ _ = True

-- 3
md3 False b = b
md3 True _ = True

-- 4
md4 a b | a == b = a
| otherwise = True

用条件表达式(conditional expressions)重新定义并运算

1
2
mc1 a b = if a == False then False else
if b == True then True else False

同上一题

1
mc2 a b = if a == True then b else False

用lambda表达式理解函数mult x y z = x * y * z

1
mult x y z == \x -> (\y -> (\z -> x * y * z))