Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Problem 4: find the number of elements in a list.
- -- Samples and displaying
- main :: IO ()
- main = mapM_ putStrLn result
- result :: [String]
- result = zipWith3 formatter [1 .. ] toEmptyList toNonEmptyList
- formatter :: (Show a) => Int -> a -> a -> String
- formatter fn el nel = "Function #"
- ++ show fn
- ++ " applied to an empty list: "
- ++ show el
- ++ ", and to a non-empty list: "
- ++ show nel
- toEmptyList = functionsList <*> [emptySampleList]
- toNonEmptyList = functionsList <*> [nonEmptySampleList]
- functionsList :: [[a] -> Int]
- functionsList = [one, two, three, four, five, six, seven, eight, nine, ten, eleven]
- nonEmptySampleList :: [Int]
- nonEmptySampleList = [10, 9 .. 0]
- emptySampleList :: [a]
- emptySampleList = []
- -- Solutions
- one :: [a] -> Int
- one = length
- two :: [a] -> Int
- two = aux 0
- where
- aux c [] = c
- aux c (_:xs) = aux (c + 1) xs
- three :: [a] -> Int
- three [] = 0
- three list = fst $ last $ zip [1 .. ] list
- four :: [a] -> Int
- four = foldl (\x _ -> x + 1) 0
- five :: [a] -> Int
- five list = last $ scanl (\x _ -> x + 1) 0 list
- six :: [a] -> Int
- six list = sum [1 | _ <- list]
- seven :: [a] -> Int
- seven list = sum $ list >>= aux
- where
- aux _ = [1]
- eight :: [a] -> Int
- eight [] = 0
- eight list = maximum $ map fst $ zip [1 .. ] list
- nine :: [a] -> Int
- nine list = sum $ map (const 1) list
- ten :: [a] -> Int
- ten list = sum $ pure (const 1) <*> list
- eleven :: [a] -> Int
- eleven [] = 0
- eleven lst = (foldl1 (.) $ map (const (+ 1)) lst) 0
- -- Function #1 applied to an empty list: 0, and to a non-empty list: 11
- -- Function #2 applied to an empty list: 0, and to a non-empty list: 11
- -- Function #3 applied to an empty list: 0, and to a non-empty list: 11
- -- Function #4 applied to an empty list: 0, and to a non-empty list: 11
- -- Function #5 applied to an empty list: 0, and to a non-empty list: 11
- -- Function #6 applied to an empty list: 0, and to a non-empty list: 11
- -- Function #7 applied to an empty list: 0, and to a non-empty list: 11
- -- Function #8 applied to an empty list: 0, and to a non-empty list: 11
- -- Function #9 applied to an empty list: 0, and to a non-empty list: 11
- -- Function #10 applied to an empty list: 0, and to a non-empty list: 11
- -- Function #11 applied to an empty list: 0, and to a non-empty list: 11
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement