Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating custom list wrapper data type

Tags:

haskell

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!

like image 527
Michael Avatar asked Jan 31 '26 03:01

Michael


2 Answers

++ 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.

like image 134
Zhu Jinxuan Avatar answered Feb 01 '26 18:02

Zhu Jinxuan


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)
like image 36
luqui Avatar answered Feb 01 '26 20:02

luqui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!