來自 99 個 Haskell 問題的問題 7
展平嵌套串列結構
這是我的解決方案:
data NestedList a = Elem a | List [NestedList a]
myFlatten :: NestedList a -> [a]
myFlatten (Elem x) = [x]
myFlatten (List (x:xs)) = x : concatMap myFlatten xs
但是,我想了解...為什么編譯器會說:
出現檢查:無法構造無限型別:a~NestedList a
預期型別:[NestedList a] 實際型別:[a]
uj5u.com熱心網友回復:
With List (x:xs), both xand xsare NestedList as, not as,因此你應該concatMap在整個串列中使用:
myFlatten :: NestedList a -> [a]
myFlatten (Elem x) = [x]
myFlatten (List xs) = concatMap myFlatten xs
為了避免在單例串列中包裝和展開,您可以使用遞回傳遞給串列的尾部,使用:
myFlatten :: NestedList a -> [a]
myFlatten = (`go` [])
where go (Elem x) = (x :)
go (List xs) = flip (foldr go) xs
uj5u.com熱心網友回復:
讓我們只檢查這部分代碼:
myFlatten :: NestedList a -> [a]
myFlatten (List (x:xs)) = x : ...
在里面List我們有x:xs,并且根據定義List我們找到(x:xs) :: [NestedList a]。因此:
x :: NestedList a
xs :: [NestedList a]
回傳的值是x : ...并且是 的型別的串列x,即NestedList a。因此,回傳型別為[NestedList a]。
但是, 的簽名myFlatten表示回傳型別是[a]. 僅當 時才有可能[a] = [NestedList a],即僅當 時a = NestedList a,但這是不可能的,因此會出現型別錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474328.html
標籤:哈斯克尔
上一篇:C#訪問堆疊物件屬性
