Exercise 6.1
import Prelude hiding ( (^) )
(^) :: Int -> Int -> Int
n ^ 0 = 1
n ^ (m+1) = n * (n^m)
Exercise 6.3
import Prelude hiding (and, concat, replicate, (!!), elem)
and :: [Bool] -> Bool
and [] = True
and (b:bs) = b && and bs
concat :: [[a]] -> [a]
concat [] = []
concat (xs:xss) = xs ++ concat xss
replicate :: Int -> a -> [a]
replicate 0 x = []
replicate (n+1) x = x : replicate n x
(!!) :: Integral a => [a] -> n -> a
(!!) (x:xs) 0 = x
(!!) (x:xs) (n+1) = xs !! n
elem :: Eq a => a -> [a] -> Bool
elem x [] = False
elem x (y:ys) = if x == y then True else elem x ys
Exercise 6.4
merge :: Ord a => [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) = if x < y then x : merge xs (y:ys) else y : merge (x:xs) ys
Exercise 6.5
halve :: [a] -> ([a], [a])
halve xs = (fsthalf, sndhalf)
where fsthalf = take ((length xs) `div` 2) xs
sndhalf = drop (length fsthalf) xs
msort :: Ord a => [a] -> [a]
msort [] = []
msort [x] = [x]
msort xs = merge (msort firsthalf) (msort secondhalf)
where
firsthalf = fst halves
secondhalf = snd halves
halves = halve xs
Exercise 6.6
import Prelude hiding (sum, take, last)
sum :: Num a => [a] -> a
sum [] = 0
sum (x:xs) = x + sum xs
take :: Int -> [a] -> [a]
take 0 xs = xs
take (n+1) (x:xs) = x : take n xs
last :: [a] -> a
last [x] = x
last (x:xs) = last xs
Niciun comentariu:
Trimiteți un comentariu