I have the following data type.
data NestedList a = Elem a | List [NestedList a]
Unfortunately, creating samples of this datatype is quite unwieldy.
List [Elem 5, Elem 6, Elem 7, List [Elem 8, Elem 9, Elem 10]]
I would like to create a helper fromList that will take a flat array of any type and give back a NestedList which is also flat but contains the same data. So I could make the sample above (excluding the part where it begins to nest) using the helper in this way:
fromList [5, 6, 7] == List [Elem 5, Elem 6, Elem 7]
This is what I have so far.
fromList :: [a] -> NestedList a
fromList [] = List[]
fromList [a] = Elem a
fromList (x:xs) = List [Elem x] ++ List [fromList xs]
The error messages are:
• Couldn't match expected type ‘[a0]’ with actual type ‘NestedList a’
• In the first argument of ‘(++)’, namely ‘List [Elem x]’
• Couldn't match expected type ‘NestedList a’ with actual type ‘[a0]’
• In the expression: List [Elem x] ++ List [fromList xs]
I'm not sure why it's telling me that I'm not returning a NestedList. I guess Haskell does not know how to natively concat my new type NestedList? Any help is appreciated!
++ is defined only for [a]. You can:
fromList :: [a] -> NestedList a
fromList [a] = Elem a
fromList x = List $ fmap Elem x
Though I do not know why you want a special case for only one element list.
You have already specified what you need quite well with your equation
fromList [5, 6, 7] == List [Elem 5, Elem 6, Elem 7]
If we just abstract
fromList xs = List (xs but with Elem applied to each element)
that is,
fromList xs = List (map Elem xs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With