PIH ex.2.5
Monday, December 31st, 2007
init', init'', init''' :: [a] -> [a]
init' xs = take (length xs - 1) xs
init'' [x] = []
init'' (x:xs) = x : init'' xs
init''' = reverse.(drop 1).reverse
init', init'', init''' :: [a] -> [a]
init' xs = take (length xs - 1) xs
init'' [x] = []
init'' (x:xs) = x : init'' xs
init''' = reverse.(drop 1).reverse
last', last'', last''' :: [a] -> a
last' xs = xs !! (length xs - 1)
last'' [x] = x
last'' (x:xs) = last'' xs
last''' = (!!0).reverse
{-
- N = a 'div' length xs
- where
- a = 10
- xs = [1,2,3,4,5]
-
- (1) N must lower case (function name)
- (2) `div`
- (3) Layout rule; identation error.
-}
n = a `div` length xs
where
a = 10
xs = [1,2,3,4,5]
Done.
( with GHCi )
2 ^ 3 * 4 = (2 ^ 3) * 4
2 * 3 + 4 * 5 = (2 * 3) + (4 * 5)
2 + 3 * 4 ^ 5 = 2 + (3 * (4 ^ 5))
-- What would be the effect of replacing <= by < in the definition of qsort?
-- qsort will return sorted list without any duplicate element.
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (x:xs) = qsort smaller ++ [x] ++ qsort larger
where
smaller = [ a | a <- xs, a < x]
larger = [ b | b <- xs, b > x]
main = do
putStrLn $ show $ qsort [2, 2, 3, 1, 1]
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (x:xs) = qsort larger ++ [x] ++ qsort smaller
where
smaller = [a | a <- xs, a <= x]
larger = [b | b <- xs, b > x]
main = do
putStrLn $ show $ qsort [3, 5, 1, 4, 2]
import Prelude hiding (product)
product :: Num a => [a] -> a
product [] = 1
product (x:xs) = x * product xs
product' :: Num a => [a] -> a
product' = foldr (*) 1
main = do
putStrLn $ show $ product[2,3,4]
sum :: (Num a) => [a] -> a
sum [] = 0
sum (x:xs) = x + sum xs
sum [x]
= { applying sum }
x + sum []
= { applying sum }
x + 0
= { applying + }
x
double x = x + x
double (double 2)
= { applying the inner double }
double (2 + 2)
= { applying + }
double 4
= { applying double }
4 + 4
= { applying + }
8
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
double (double 2)
= { applying the outer double }
double 2 + double 2
= { applying the first double }
(2 + 2) + double 2
= { applying the first + }
4 + double 2
= { applying double }
4 + (2 + 2)
= { applying the second + }
4 + 4
= { applying + }
8
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
double (double 2)
= { applying the inner double }
double (2 + 2)
= { applying double }
(2 + 2) + (2 + 2)
= { applying first + }
4 + (2 + 2)
= { applying second + }
4 + 4
= { applying + }
8