Skip to content

Commit db80208

Browse files
committed
add recursion
1 parent 04e8379 commit db80208

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

README.md

+22
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ By <b>Jeffrey Liu</b>
66
Contents
77
---
88
1. [Basic Typeclass](#title1)
9+
2. [Elegent of Haskell](#title2)
910

1011
### <a name="title1"></a> Basic Typeclass
1112
----
@@ -41,3 +42,24 @@ Contents
4142
* Use **fromIntegral** to parse Integral to Num, ```fromIntegral (length [1,2,3,4]) + 3.2```
4243
9. Floating
4344
* Types in this class: Float, Double
45+
46+
<br />
47+
48+
49+
### <a name="title2"></a> Elegant of Haskell
50+
----
51+
1. Fibonacci
52+
```haskell
53+
fibs :: [Integer]
54+
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
55+
```
56+
57+
2. QuickSort
58+
```haskell
59+
quicksort :: (Ord a) => [a] -> [a]
60+
quicksort [] = []
61+
quicksort (x:xs) =
62+
let smallerSorted = quicksort [a | a <- xs , a <= x]
63+
biggerSorted = quicksort [a | a <- xs, a > x]
64+
in smallerSorted ++ [x] ++ biggerSorted
65+
```

recursion.hs

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
maximum' :: (Ord a) => [a] -> a
2+
maximum' [] = error "maximum of empty list"
3+
maximum' [x] = x
4+
maximum' (x:xs) = max x (maximum' xs)
5+
{- | x > maxTail = x
6+
| otherwise = maxTail
7+
where maxTail = maximum' xs -}
8+
9+
replicate' :: (Num i, Ord i) => i -> a -> [a]
10+
replicate' i a
11+
| i <= 0 = []
12+
| otherwise = a:replicate' (i-1) a
13+
14+
take' :: (Num i, Ord i) => i -> [a] -> [a]
15+
take' n _
16+
| n <= 0 = []
17+
take' _ [] = []
18+
take' n (x:xs) = x : take' (n-1) xs
19+
20+
reverse' :: [a] -> [a]
21+
reverse' [] = []
22+
reverse' (x:xs) = reverse' xs ++ [x]
23+
24+
repeat' :: a -> [a]
25+
repeat' x = x : repeat' x
26+
27+
zip' :: [a] -> [a] -> [(a,a)]
28+
zip' _ [] = []
29+
zip' [] _ = []
30+
zip' (x:xs) (y:ys) = (x,y) : zip' xs ys
31+
32+
elem' :: (Eq a) => a -> [a] -> Bool
33+
elem' a [] = False
34+
elem' a (x:xs) = if (a == x) then True
35+
else elem' a xs
36+
{- elem' a (x:xs)
37+
| a == x = True
38+
| otherwise = a `elem'` xs -}
39+
40+
-- Classic QuickSort!
41+
quicksort :: (Ord a) => [a] -> [a]
42+
quicksort [] = []
43+
quicksort (x:xs) =
44+
let smallerSorted = quicksort [a | a <- xs , a <= x]
45+
biggerSorted = quicksort [a | a <- xs, a > x]
46+
in smallerSorted ++ [x] ++ biggerSorted

0 commit comments

Comments
 (0)