I have a tree defined in Haskell like:
data NTree a = Nil | Tree a [NTree a] deriving Show
I want to 'flatten' the tree so that all the nodes appear in a list. I'm trying to do so by:
arrayify :: NTree Int -> [Int]
arrayify (x:xs) = x ++ arrayify xs
I can kind of tell that this is wrong, but I have no idea how to fix this. For reference, this is the error I'm getting:
• Couldn't match expected type ‘NTree Int -> [Int]’
with actual type ‘[Int]’
• Possible cause: ‘(++)’ is applied to too many arguments
In the expression: x ++ arrayify xs
In an equation for ‘arrayify’: arrayify = x ++ arrayify xs
Since
arrayifyexpects anNTree Int, you probably want to pattern match on the two data constructors, so:For the
Emptycase, you should return an empty list, for theTree v tsyou can make a list that starts withvand then has thearrayifys of the elements oftsas children. You can use the(:) :: a -> [a] -> [a]andconcatMap :: Foldable f => (a -> [b]) -> f a -> [b]for this.But instead of writing
arrayifyyourself, you can let Haskell derive an instance ofFoldablefor yourNTree:Then you can call
toList :: Foldable f => f a -> [a]on anNTreeobject.