In [1]:
-- 练习递归写函数
In [2]:
-- maximun'
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "empty is error"
maximum' [x] = x
maximum' (x:xs) = max x (maximum' xs)
In [3]:
maximum' [2, 5, 1]
In [4]:
-- replicate
replicate' :: Int -> a -> [a]
replicate' n x
| n <= 0 = []
| otherwise = x: replicate' (n-1) x
In [5]:
replicate' 3 5
In [7]:
-- take me
take' :: (Num i, Ord i) => i -> [a] -> [a]
take' n _
| n <= 0 = []
take' _ [] = []
take' n (x:xs) = x: take' (n-1) xs
In [8]:
-- reverse
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = xs ++ [x]
In [9]:
repeat' :: a -> [a]
repeat' x = x:repeat' x
In [11]:
take 5 (repeat' 5)
In [15]:
-- zip
zip' :: [a] -> [b] -> [(a, b)]
zip' _ [] = []
zip' [] _ = []
zip' (x:xs) (y:ys) = (x,y): zip' xs ys
In [16]:
zip' [1, 2, 3] ['a', 'b']
In [18]:
-- elem
elem' :: (Eq a) => a -> [a] -> Bool
elem' a [] = False
elem' a (x:xs)
| a == x = True
| otherwise = a `elem'` xs
In [21]:
-- quick sort
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smaller = [a | a <- xs, a <= x]
larger = [a | a <- xs, a > x]
in quicksort smaller ++ [x] ++ quicksort larger
In [23]:
quicksort [10, 2, 5, 3, 1, 6, 7]