這裏是我的功能無法匹配打印嵌套列表的Haskell代碼中的預期類型?
data Item a = One a | Many [Item a]
let flat (One x) = show x
let flat (Many xs) = show xs
這裏是輸出
Prelude> flat [[3]]
<interactive>:21:6:
Couldn't match expected type ‘Item t0’ with actual type ‘[[t1]]’
In the first argument of ‘flat’, namely ‘[[3]]’
In the expression: flat [[3]]
In an equation for ‘it’: it = flat [[3]]
它看起來像平坦的不承認項目作爲其函數簽名,所以我試圖重新定義函數簽名
flat :: Item a -> [a]
<interactive>:22:1:
Couldn't match type ‘a1’ with ‘Char’
‘a1’ is a rigid type variable bound by
an expression type signature: Item a1 -> [a1] at <interactive>:22:1
Expected type: Item a1 -> [a1]
Actual type: Item a1 -> String
In the expression: flat :: Item a -> [a]
In an equation for ‘it’: it = flat :: Item a -> [a]
但Haskell不會讓你在ghci中重新定義函數簽名,有沒有辦法解決這個問題?
我懷疑你的意思是'One a |許多[a]'。 – 9000
難道你不想'平(多['3'])'?或者沒有類型簽名的'flat(Many [3])'。 – ErikR
啊,這是意想不到的,我想我要做的是平坦化一個任意深度的嵌套列表(我正在通過打印出來的東西進行調試),我想我可以定義一個新的數據結構來做到這一點,但它似乎我實際上必須爲每個元素定義類型?這似乎破壞了目的。有沒有辦法模式匹配Many vs One – Kevin