Programming in Haskell 是一本入门Haskell的好书,介绍页面以及配套的slides, vedios, codes都在这里 。
这一章节就是在讲递归,所以下面的定义都是默认用递归定义。
定义幂函数
1 2 3 4 5 6 7 8 9 10 mypow :: Int -> Int -> Int mypow _ 0 = 1 mypow x n = x * mypow x (n-1 )
解释length
, drop
, init
的递归求值过程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
定义以下库函数
and
1 2 3 4 5 6 7 8 9 10 11 myand :: [Bool ] -> Bool myand [] = True myand (n : ns) | n == False = False | otherwise = myand ns
concat
1 2 3 4 5 6 7 8 9 10 11 myconcat :: [[a]] -> [a]myconcat [] = []myconcat [[a]] = [a]myconcat (n : ns) = n ++ myconcat ns
replicate
1 2 3 4 5 6 7 8 9 10 11 12 myreplicate :: Int -> a -> [a]myreplicate 0 _ = []myreplicate n a = a : myreplicate (n - 1 ) a
(!!)
1 2 3 4 5 6 7 8 9 10 mynth :: [a] -> Int -> amynth (x : xs) 0 = xmynth (x : xs) n = mynth xs (n - 1 )
elem
1 2 3 4 5 6 7 8 9 10 11 12 myelem :: Eq a => a -> [a] -> Bool myelem x [] = False myelem x (n : ns) | x == n = True | otherwise = myelem x ns
定义merge
函数
merge: 将两个有序list合并成一个有序list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 merge :: Ord a => [a] -> [a] -> [a]merge [] [] = []merge a [] = amerge [] a = amerge (n:ns) (x:xs) | x >= n = n : merge ns (x:xs) | x < n = x : merge (n:ns) xs
利用merge
定义归并排序msort
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 halve :: [a] -> ([a], [a])halve xs = let hl = (length xs) `div` 2 in (take hl xs, drop hl xs) msort :: Ord a => [a] -> [a]msort [] = []msort [a] = [a]msort xs = merge (msort (fst (halve xs))) (msort (snd (halve xs)))
定义sum
, take
, last
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 mysum :: Num a => [a] -> amysum [] = 0 mysum (x : xs) = x + mysum xsmytake :: Int -> [a] -> [a]mytake 0 _ = []mytake _ [] = []mytake n (x : xs) = x : mytake (n - 1 ) xsmylast :: [a] -> amylast [x] = xmylast (x : xs) = mylast xs