Archive for December, 2007

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

PIH ex.2.4

Monday, December 31st, 2007

last', last'', last''' :: [a] -> a

last' xs = xs !! (length xs - 1)

last'' [x]    = x
last'' (x:xs) = last'' xs

last''' = (!!0).reverse

PIH ex.2.3

Monday, December 31st, 2007

{-
 - 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.
 -}= a `div` length xs
    where
      a = 10
      xs = [1,2,3,4,5]

PIH ex.2.2

Monday, December 31st, 2007

Done. :-) ( with GHCi )

PIH ex.2.1

Monday, December 31st, 2007

2 ^ 3 * 4      =  (2 ^ 3) * 4
2 * 3 + 4 * 5  =  (2 * 3) + (4 * 5)
2 + 3 * 4 ^ 5  =  2 + (3 * (4 ^ 5))

PIH ex.1.5

Monday, December 31st, 2007

-- 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 [22311]

PIH ex.1.4

Monday, December 31st, 2007

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 [35142]

PIH ex.1.3

Monday, December 31st, 2007

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]

PIH ex.1.2

Monday, December 31st, 2007

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

PIH ex.1.1

Monday, December 31st, 2007

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