2013-04-08 55 views
3

我試圖製作一個包含子列表的列表,如[1, 2, [3, 4], [3, [4, 5]]]在Haskell中創建以下列表[1,2,[3,4],[3,[4,5]]]

看來我應該定義一個新類型。我試過了:

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

但是我覺得它錯了,或者說我不知道​​如何使用它。我對Haskell很新,我不確定這個表達的含義。

這是否意味着這是有「型」 Int與參數a和帶有參數[NestedList a]「類型」 List?上述

data表達從solution帶到99 Haskell questions

(**)拼合嵌套列表結構的第七鍛鍊。

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

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

,但是當我在ghci打電話flatten [[1,2], 3]我得到的

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

http://codegolf.stackexchange.com/questions/113238/is-it-true-ask-jelly/113416#113416 – leftaroundabout 2017-03-21 18:07:04

回答

9

錯誤你不能叫flatten [[1,2],3]因爲你的扁平化應該採取NestedList a,而不是一個正常的嵌套列表,其中ISN甚至不允許在Haskell中使用。

您的電話應該是這樣的

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

他說'[[1,2],3]'與haskell中的'NestedList'不是同一類型,即使出現與'data MyInt = Int'和'Int'不一樣。而他的另一點'[1,2]'是'Num'的列表,'3'是一個Num所以'[[1,2],3]'甚至不允許,因爲'[1,2]''與'3'不同。 – DiegoNolan 2013-04-08 18:08:58

+0

當我寫:t [1,2,[3]]我得到[1,2,[3]] ::(Num t,Num [t])=> [[t]]但我不知道如何做一個新的類型,讓我有這樣一個列表。 – user2254424 2013-04-08 18:17:13

+0

像'[1,2,3]'這樣的東西只是用於編寫'1:2:3:[]'的一些特殊的語法糖,我不認爲你可以使用'[1,2,3]'適用於您自己的數據類型的符號。現在對於你定義的數據類型,有兩個構造函數,'List'和'Elem'。 md2perpe已經展示瞭如何使用這些示例。如果你想要一段代表'[[1,2],3]'的數據(你不能使用普通列表),你可以編寫List [List [Elem 1,Elem 2],Elem 3] ' – tauli 2013-04-08 19:00:22

7

這是一個方面說明,我可以不適合評論。這並不直接回答你的問題,但我認爲你可能會發現它有用。

您的類型與Forest相同。請參閱中的containers包,其中implements this type適合您。

它甚至還包括一個flatten功能:

flatten :: Tree a -> [a] 

...你也可以僅僅通過使用concatMap使一個Forest工作:

concatMap flatten :: Forest a -> [a]