list - Haskell - 如何计算嵌套列表中的元素

标签 list haskell overloading counting

假设我嵌套了 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 不会。

1Int 类型,而 [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/

相关文章:

python - Matplotlib 3D 震源图,从 .txt 文件中读取 xyz 值

python - 将嵌套列表转换为 numpy 数组的有效方法

元组的 Python 数组首先分组,然后存储

haskell - 使用 Biapplicative 遍历

scala - 选项方法签名,功能已在此范围内定义

go - 在 Go 中有点 "method overloading"?

c# - 将 ICollectionView 转换为 List<T>

haskell - Haskell 中提升和未提升的产品类型是什么?

haskell - 高效冒泡排序

C++运算符重载——指针、乘法