-
Notifications
You must be signed in to change notification settings - Fork 0
/
recursion.hs
52 lines (42 loc) · 1.3 KB
/
recursion.hs
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
--- Recursion is important to Haskell because unlike imperative languages,
--- you do computations in Haskell by declaring what something is
--- instead of declaring how you get it.
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list"
maximum' [x] = x
maximum' (x: xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maximum' xs
maximum'' :: (Ord a) => [a] -> a
maximum'' [] = error "maximum of Empty List"
maximum'' [x] = x
maximum'' (x:xs) = max x (maximum'' xs)
--- maximum [2,5,1] = max 2 (maximum[5,1] = max 5 (maximum[1]))
replicate' :: (Num i, Ord i) => i -> a -> [a]
replicate' n x
| n <= 0 = []
| otherwise = x:replicate' (n-1) x
take' :: (Num i, Ord i) => i -> [a] -> [a]
take' n _
| n <= 0 = []
take' _ [] = []
take' n (x : xs) = x : take'(n - 1) xs
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]
zip' :: [a] -> [b] -> [(a, b)]
zip' _ [] = []
zip' [] _ = []
zip' (x: xs) (y:ys) = (x, y):zip' xs ys
elem' :: (Eq a) => a -> [a] -> Bool
elem' a [] = False
elem' a (x: xs)
| a == x = True
| otherwise = a `elem'` xs
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerSorted = quicksort [a | a <- xs, a <= x]
biggerSorted = quicksort [a | a <- xs, a > x]
in smallerSorted ++ [x] ++ biggerSorted