2
\$\begingroup\$

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))))
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Well, unless you wanted to add instances to allow for folding and so, or conversions to Data.List I'd say that's perfect as it is.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.