假设我嵌套了 lsit: [1, [2, 3, 4], [5, [6]]] 我想计算它有多少个元素。在这种情况下,它是六个元素。我为此编写了这样的代码:
totalElems :: [a] -> Int
totalElems (x:xs) = case (x, xs) of
(_, []) -> 0
(y:ys, _) -> 1 + totalElems ys + totalElems xs
(_, _) -> 1 + totalElems xs
但是我有一个错误:
a.hs:4:42:
Couldn't match expected type ‘a’ with actual type ‘[a0]’
‘a’ is a rigid type variable bound by
the type signature for totalElems :: [a] -> Int at a.hs:1:15
Relevant bindings include
xs :: [a] (bound at a.hs:2:15)
x :: a (bound at a.hs:2:13)
totalElems :: [a] -> Int (bound at a.hs:2:1)
In the pattern: y : ys
In the pattern: (y : ys, _)
In a case alternative:
(y : ys, _) -> 1 + totalElems ys + totalElems xs
我如何在 Haskell 中做到这一点?
最佳答案
你不能像在 Haskell 中那样创建自由形式的列表中列表。动态类型的语言会容忍这样的愚蠢行为,但强类型的 Haskell 不会。
1
是 Int
类型,而 [2,3,4]
是不同的类型 [Int]
。列表中的内容必须属于同一类型。
但是,您可以这样做:
data Nest a = Elem a | List [Nest a]
example ::Nest Int
example = List [Elem 1, List [Elem 2, Elem 3, Elem 4], List [Elem 5, List [Elem 6]]]
countNest :: Nest a -> Int
countNest (Elem x) = 1
countNest (List xs) = sum $ map countNest xs
关于list - Haskell - 如何计算嵌套列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235155/