二叉树上的FOLD在haskell中的应用
我有一个实现二叉树的小haskell代码。我想在树上应用一个折叠函数。这是密码-二叉树上的FOLD在haskell中的应用,haskell,functional-programming,binary-tree,Haskell,Functional Programming,Binary Tree,我有一个实现二叉树的小haskell代码。我想在树上应用一个折叠函数。这是密码- data Btree a = Tip a | Bin (Btree a) (Btree a) deriving Show foldbtree :: (a->a->a) -> Btree a-> a foldbtree f (Tip x) = x foldbtree f (Bin t1 t2) = (foldbtree f t1) f (foldbtree f t2) 但我得到了编译错误-
data Btree a = Tip a | Bin (Btree a) (Btree a) deriving Show
foldbtree :: (a->a->a) -> Btree a-> a
foldbtree f (Tip x) = x
foldbtree f (Bin t1 t2) = (foldbtree f t1) f (foldbtree f t2)
但我得到了编译错误-
Occurs check: cannot construct the infinite type:
t2 = t0 -> t1 -> t2
In the return type of a call of `foldbtree'
Probable cause: `foldbtree' is applied to too many arguments
In the expression: (foldbtree f t1) f (foldbtree f t2)
In an equation for `foldbtree':
foldbtree f (Bin t1 t2) = (foldbtree f t1) f (foldbtree f t2)
bird_exercise.hs:206:47:
Occurs check: cannot construct the infinite type:
t1 = t0 -> t1 -> t2
In the return type of a call of `foldbtree'
Probable cause: `foldbtree' is applied to too few arguments
In the fourth argument of `foldbtree', namely `(foldbtree f t2)'
In the expression: (foldbtree f t1) f (foldbtree f t2)
请帮我解决这个问题。谢谢。在最后一种情况下,您需要的是:
foldbtree f (Bin t1 t2) = f (foldbtree f t1) (foldbtree f t2)
事实上,您可能应该“作弊”,让GHC使用
DeriveFoldable
扩展名自动为您派生数据类型的Foldable
实例:
{-# LANGUAGE DeriveFoldable #-}
module XXX where
import Data.Foldable (Foldable, foldMap)
import Data.Monoid (Sum(..))
data Btree a = Tip a | Bin (Btree a) (Btree a) deriving (Show, Foldable)
sumTips :: Btree Int -> Int
sumTips = getSum . foldMap Sum
(相关位是.hs文件顶部的{-#LANGUAGE DeriveFoldable#-}
pragma和数据类型定义中的派生(…,Foldable…)
子句。)fold
,foldMap
,从编译器派生的Btree
实例Foldable
中得到的类几乎肯定是您想要的类。当您使用时,您可能还希望派生Functor
和可遍历的
实例,这与可折叠的
完全相同。如果愿意,您可以通过cabal或命令行传递DeriveXXX
pragmas,尽管我喜欢每个文件pragmas的特殊性。或者:(foldbtree f t1)`f`(foldbtree f t2)