本文介绍了用于泛型Haskell树的通用foldr和foldl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b <$ p

$ p> 的第三个参数。 code>

  • foldr 期望其第三个参数的类型为 [c]


    所以你需要处理 ts 到类型为 [c] ,并将结果传递给 foldr 而不是 ts 本身。 功能应该是一个好地方开始。


    How can I write generalized foldr and foldl function for generic Haskell trees, given this definition?

    data (Eq a, Show a) => Tree a = Void | Node a [Tree a]
        deriving (Eq, Show)
    
    treefoldr :: (Eq a, Show a) => 
       (a -> b -> c) -> c -> (c -> b -> b) -> b -> Tree a -> c
    
    treefoldl :: (Eq a, Show a) =>
       (b -> a -> c) -> c -> (c -> b -> b) -> b -> Tree a -> c
    

    Even if I can understand how foldr and foldl functions work in Haskell, I'm not quite sure how to write this generalized function for trees.

    EDIT: I tried something like this (not even compiling):

    treefoldr  _ g1 _ _    Void       = g1
    treefoldr f1 g1 f2 g2 (Node a ts) = f1 a (foldr f2 g2 ts)
    

    EDIT 2: another try...

    treefoldr _ z1 _ _   Void      = z1
    treefoldr f z1 g z2 (Node a ts) =
       f a (foldr g z2 (map (\x -> treefoldr f z1 g z2 x) ts))
    
    treefoldl _ z1 _ _   Void      = z1
    treefoldl f z1 g z2 (Node a ts) =
       f (foldl g z2 (map (\x -> treefoldl f z1 g z2 x) ts)) a
    

    treefoldr is working, however treefoldl not:

    解决方案

    The error message in full:

    Couldn't match expected type `c' against inferred type `Tree a'
      `c' is a rigid type variable bound by
          the type signature for `treefoldr' at so.hs:5:14
      Expected type: [c]
      Inferred type: [Tree a]
    In the third argument of `foldr', namely `ts'
    In the second argument of `f1', namely `(foldr f2 g2 ts)'
    

    That means that

    • ts is of type [Tree a]
    • you are using it as the third argument to foldr
    • foldr expects its third argument to be of type [c]
    • [c] and [Tree a] are different types, hence this is an error

    So you need to process ts into something of type [c] and pass that result to foldr instead of ts itself. The map function would be a good place to start.

    这篇关于用于泛型Haskell树的通用foldr和foldl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 10-09 23:49