-
Notifications
You must be signed in to change notification settings - Fork 2
/
Problem05.hs
43 lines (35 loc) · 883 Bytes
/
Problem05.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
module Problem05 where
-- Problem 5:
-- reverse a list
myReverse :: [a] -> [a]
myReverse = foldl (flip (:)) []
{-
example: [1,2,3,4]
=> 1:2:3:4:[] ([])
=> 2:3:4:[] (1:[])
=> 3:4:[] (2:1:[])
=> 4:[] (3:2:1:[])
=> [] (4:3:2:1:[])
-}
-- drawback: (++) and (:[]) are costly
myReverse1 :: [a] -> [a]
myReverse1 [] = []
myReverse1 (x:xs) = myReverse1 xs ++ [x]
-- avoids (++) and (:[]) totally, but needs `init` and `last'
myReverse2 :: [a] -> [a]
myReverse2 xs
| null xs = []
| otherwise = last xs : myReverse2 (init xs)
{-
last xs : myReverse2 (init xs)
> (flip (:)) (myReverse2 (init xs)) (last xs)
> (flip (:) (myReverse2 ys) y -- let (ys,y) = (init &&& last) xs
> (flip (:) reversed y) -- let reversed = myReverse2 ys
-}
main :: IO ()
main = do
let d :: [Int]
d = [1..10]
print $ myReverse d
print $ myReverse1 d
print $ myReverse2 d