rnd*_*rnd 2 haskell overloading list 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不会.
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