1 martie 2010

Haskell exercises - Chapter 4

My solutions to exercises from Graham Hutton's Programming in Haskell.


Exercise 4.1

halve :: [a] -> ([a], [a])
halve xs
| len `mod` 2 == 0 = (take (len `div` 2) xs, drop (len `div` 2) xs)
| otherwise = (xs, [])
where len = length xs


Exercise 4.2
a)

safetail :: [a] -> [a]
safetail xs = if null xs then [] else tail xs

b)

safetail :: [a] -> [a]
safetail xs | null xs = []
| otherwise = tail xs

c)

safetail :: [a] -> [a]
safetail [] = []
safetail xs = tail xs


Exercise 4.3

(||) :: Bool -> Bool -> Bool

First method:

(||) True True = True
(||) True False = True
(||) False True = True
(||) False False = False

Second method:

(||) False False = False
(||) _ _ = True

Third method:

(||) False q = q
(||) True _ = True

A variation of the 3rd method:

(||) True _ = True
(||) _ q = q

Fourth method:

(||) p q | p == q = p
| otherwise = True


Exercise 4.4

(&&) :: Bool -> Bool -> Bool
p && q = if p
then
if q then True else False
else
False


Exercise 4.5

(&&) :: Bool -> Bool -> Bool
p && q = if p then q else False


Exercise 4.6

mult :: Num a => a -> (a -> (a -> a))
mult = \x -> (\y -> (\z -> x * y * z))

Niciun comentariu:

Trimiteți un comentariu