Given the following definition of Cons
:
data Cons a = Cons a (Cons a)
| Empty
deriving Show
I implemented a flatten
function.
It's mean to work exactly like concat :: [[a]] -> [a]
, but for Cons
.
flatten :: Cons (Cons a) -> Cons a
flatten Empty = Empty
flatten (Cons (Empty) ys) = flatten ys
flatten (Cons (Cons x xs) ys) = Cons x (flatten (Cons xs ys))
Test data:
test1 :: Cons (Cons Int)
test1 = Cons (Cons 5 Empty) Empty
test2 :: Cons (Cons Int)
test2 = Cons (Cons 5 (Cons 10 Empty)) Empty
test3 :: Cons (Cons Int)
test3 = Cons (Cons 5 (Cons 10 (Cons 20 Empty))) test2
Some tests:
ghci> flatten test1
Cons 5 Empty
ghci> flatten test2
Cons 5 (Cons 10 Empty)
ghci> flatten test3
Cons 5 (Cons 10 (Cons 20 (Cons 5 (Cons 10 Empty))))