reverse :: [a] -> [a] reverse [] = [] reverse (x:xs) = reverse xs ++ [x]
++
(++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x:(xs ++ ys)
xs++ys
length xs
reverse xs
:set +s
in GHCi to turn on time and memory stats.
:set +s
sum [1..10000]
50005000
(0.01 secs, 2,633,512 bytes)
sum (reverse [1..10000])
50005000
(1.56 secs, 4,455,178,368 bytes)
reverse
reverse :: [a] -> [a]
reverse xs = revOnto xs []
-- revOnto xs rs = reverse xs ++ rs
revOnto :: [a] -> [a] -> [a]
revOnto [] rs = rs
revOnto (x:xs) rs = revOnto xs (x:rs)
revOnto
reverse [1,2,3]
revOnto [1,2,3] []
revOnto [2,3] [1]
revOnto [3] [2,1]
revOnto [] [3,2,1]
[3,2,1]
reverse xs
sum (reverse [1..10000])
50005000
(0.01 secs, 3,916,656 bytes)
sum (reverse [1..1000000])
500000500000
(0.89 secs, 386,901,184 bytes)
data Q a -- the type of queues empty :: Q a -- an empty queue add :: a -> Q a -> Q a -- add an element at the back isEmpty :: Q a -> Bool -- check if the queue is empty front :: Q a -> a -- inspect the front element remove :: Q a -> Q a -- remove an element from the front
Q
data Q a = Q [a] deriving (Eq,Show) empty = Q [] add x (Q xs) = Q (xs++[x]) isEmpty (Q xs) = null xs front (Q (x:xs)) = x remove (Q (x:xs)) = Q xs
add 5 (add 4 (add 3 (add 2 (add 1 empty))))
data Q a = Q [a] [a] deriving Show
reverse
empty = Q [] [] add x (Q fs bs) = Q fs (x:bs) isEmpty (Q fs bs) = null fs && null bs front (Q (f:fs) bs) = x front (Q [] bs) = head (reverse bs) remove (Q (f:fs) bs) = Q fs bs remove (Q [] bs) = Q (tail (reverse bs)) []
smartQ
Q
smartQ [] bs = Q (reverse bs) [] smartQ fs bs = Q fs bs
empty = smartQ [] [] add x (Q front back) = smartQ front (x:back) isEmpty (Q front back) = null front front (Q (x:_) _) = x remove (Q (x:front) back) = smartQ front back
smartQ
Q [1] [4,3,2] == Q [1,2] [4,3] == Q [1,2,3,4] []
Eq
Eq
instance Eq a => Eq (Q a) where q1 == q2 = toList q1 == toList q2 toList (Q front back) = front ++ reverse back
module Queue(Q,empty,add,remove,front,isEmpty) where data Q a = Q [a] [a] deriving Show empty = smartQ [] [] -- ... -- ...
Q
Q
smartQ
toList
module
Queue(Q,…)
where
Q
Q
module
Queue(Q(..),…)
where
Q
module Queue where
module Queue() where