{-
    Opgaver pĺ ugeseddel 3 til kapitel 9
-}
module Uge3_9 where

-- Opgave 9.1

doubleAll1 :: [Int] -> [Int]
doubleAll1 xs = [2*x | x <- xs]

doubleAll2 :: [Int] -> [Int]
doubleAll2 [] = []
doubleAll2 (x:xs) = 2*x : doubleAll2 xs

doubleAll3 :: [Int] -> [Int]
doubleAll3 xs = map (2*) xs

doubleAll4 :: [Int] -> [Int]
doubleAll4 = map (2*)


-- Opgave 9.2

one :: a -> Int
one _ = 1

length2 :: [a] -> Int
length2 = sum . map one

-- eller:

length3 :: [a] -> Int
length3 = sum . map (\ _ -> 1)


-- Opgave 9.3

greaterEqOne x = x >= 1
addOne = (1+)

addUp ns = map addOne (filter greaterEqOne ns)


-- Opgave 9.4

-- Diskutér

-- Opgave 9.9

iter :: Int -> (a -> a) -> a -> a
iter n f x
    | n <= 0     = x
    | otherwise  = iter (n-1) f (f x)

-- Opgave 9.10

double :: Int -> Int
double = (2*)

power2 :: Int -> Int
power2 n =  iter n double 1
	    

-- Opgave 9.14

sing x = [x]

mystery xs = foldr (++) [] (map sing xs)

-- diskutér


-- Opgave 9.16

filterFirst :: (a -> Bool) -> [a] -> [a]
filterFirst _ [] = []
filterFirst p (x:xs)
    | p x        = x : filterFirst p xs
    | otherwise  = xs 


-- Opgave 9.17

filterLast :: (a -> Bool) -> [a] -> [a]
filterLast p [] = []
filterLast p (x:xs)
    | p x                      = x : rest
    | length xs == length rest =     rest
    | otherwise                = x : rest
    where
      rest = filterLast p xs

filterLast2 :: (a -> Bool) -> [a] -> [a]
filterLast2 p = reverse . filterFirst p . reverse

