Create the following list [1, 2, [3, 4], [3, [4, 5]]] in Haskell

亡梦爱人 提交于 2021-02-10 03:10:36

问题


I'm trying to make a list that contains sub lists, like [1, 2, [3, 4], [3, [4, 5]]].

It seems like I should define a new type. I tried:

data NestedList a = Int a | List [NestedList a]

but I think its wrong, or that I don't know how to use it. I'm very new to Haskell and I'm not sure about the meaning of this expression.

Does it mean that it is making a "type" Int with parameter a and a "type" List with parameter [NestedList a]?

The data expression above was taken from the solution to the 7th exercise of the 99 Haskell questions

(**) Flatten a nested list structure.

data NestedList a = Elem a | List [NestedList a]

flatten :: NestedList a -> [a]
flatten (Elem x) = [x]
flatten (List x) = concatMap flatten x

but when I call flatten [[1,2], 3] in ghci I get the error of

couldn't match expected type 'NestedList a0' with actual type '[t0]'

回答1:


You can't call flatten [[1,2],3] because your flatten should take a NestedList a, not a nested normal list, which isn't even allowed in Haskell.

Your call should be something like

flatten (List [Elem 3, List [Elem 2, Elem 4], Elem 5])



回答2:


This is a side note that I couldn't fit in a comment. This does not directly answer your question but I thought you might find it useful.

Your type is the same as a Forest. See Data.Tree in the containers package, which implements this type for you.

It even includes a flatten function:

flatten :: Tree a -> [a]

... which you can make work for a Forest too just by using concatMap:

concatMap flatten :: Forest a -> [a]


来源:https://stackoverflow.com/questions/15884984/create-the-following-list-1-2-3-4-3-4-5-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!