-------------------------------------------------------------------------------- -- Ex. 1 interleave :: a -> [a] -> [[a]] interleave x [] = [[x]] interleave x (y:ys) = [x:y:ys] ++ map (y:) (interleave x ys) {- interleave 3 [1,2,3] => [[3,1,2,3],[1,3,2,3],[1,2,3,3],[1,2,3,3]] -} -------------------------------------------------------------------------------- -- Ex. 2 perms :: [a] -> [[a]] perms [] = [[]] perms (x:xs) = [zs | ys <- perms xs, zs <- interleave x ys] {- perms [1,2,3] => [[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]] -} -------------------------------------------------------------------------------- -- Ex. 3 data Matrix a = M [[a]] instance (Show a) => Show (Matrix a) where show (M xs) = concatMap showRow xs where showRow = foldr (\x rest -> (show x) ++ " " ++ rest) "\n" map2 :: (a -> a -> a) -> [a] -> [a] -> [a] map2 f xs [] = [] map2 f [] ys = [] map2 f (x:xs) (y:ys) = (f x y):(map2 f xs ys) matAdd :: (Num a) => Matrix a -> Matrix a -> Matrix a matAdd (M xs) (M ys) = M (map2 (\x y -> map2 (+) x y) xs ys) -------------------------------------------------------------------------------- -- Ex. 4 e :: Double -> Double e n = foldl (\x y -> x + (1 / (fac y))) 0.0 [0..n] where fac 0 = 1 fac n = n * (fac (n-1)) --------------------------------------------------------------------------------