我有一個名單的定義問題。通常列表定義爲data [a] = [] | a : [a]
但如果我寫這樣的事情在我的代碼,具體我會定義data T a = N | a -> (T a)
解釋給我一個錯誤:名單的標準定義
Malformed head of type or class declaration
你知道什麼是錯的? 。
我有一個名單的定義問題。通常列表定義爲data [a] = [] | a : [a]
但如果我寫這樣的事情在我的代碼,具體我會定義data T a = N | a -> (T a)
解釋給我一個錯誤:名單的標準定義
Malformed head of type or class declaration
你知道什麼是錯的? 。
a -> T a
意味着a是一個函數,返回T a
的東西,所以我認爲這是錯誤的一點。嘗試這樣的事情。
data T a = N | R a (T a)
N爲空列表值([]
的當量),R是值構造(相當於:
)
你需要隨身攜帶的a
價值的一些方法的右手邊。你現在可以正確的列表像。
> N -- The empty List
> R 5 N -- a list with a single element and then the end
> R 7 (R 6 (R 5 N)) -- the list 7, 6, 5
它看起來像你的問題是,你試圖用->
中綴構造像:
(爲了建立使用a -> b -> N
語法列表)。這是不允許的,因爲Haskell中的自定義中綴構造函數必須以:
字符開頭。
的原因嗎?奇怪的錯誤訊息是因爲->
在Haskell被保留用於函數類型,如Jeff's answer解釋
試試這個:
-- Create a right-associative infix constructor.
data T a = N | a :-> (T a)
infixr :->
mylist :: T Int
mylist = 10 :-> 17 :-> N
--If we hadn't made the operator right associative,
-- we would need to use explicit parenthesis here
myotherlist :: T Int
myotherlist = 10 :-> (17 :-> N)
-- Example function
isempty :: T a -> Bool
isempty N = False
isempty (_ :-> _) = True
表情符號比箭頭看起來好多了。 – Landei 2011-04-08 19:05:38
謝謝你,但我讀了( - >)是其中一個數據構造函數。真正意義上的定義一個沒有固定數量參數的函數。例如,總結它們的參數的函數:sum 5 = 5;總和5 4 = 9 ...所以我必須定義一個數據結構,使用( - >) – 877 2011-04-08 15:33:00
( - >)是一個* type *構造函數,而不是數據構造函數。 ( - >)有兩種類型(比如a和b),並返回一個* type *,表示從a類型的對象到b類型的對象的函數。 – dvitek 2011-04-08 15:43:55
@ 877:在Haskell中定義一個可變參數函數有些困難:它的類型是什麼?這是可能的(參見['Text.Printf'](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Text-Printf.html)模塊),但它很少是你想要的。更常見的解決方案是讓你的功能列表。事實上,在Prelude中,有一個函數['sum'](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:sum),它有'數字a => [a] - > a'。 – 2011-04-08 21:00:52