[英]Applying FOLD on Binary tree in haskell
I have a small haskell code which implement binary tree. 我有一个小的haskell代码实现二叉树。 I want to apply a fold function on the tree.
我想在树上应用折叠功能。 Here is the code-
这是代码 -
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)
But I am getting compilation error - 但我收到编译错误 -
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)
Please help me regarding this. 请帮我解决这个问题。 Thank you.
谢谢。
在最后一种情况下你需要的是:
foldbtree f (Bin t1 t2) = f (foldbtree f t1) (foldbtree f t2)
In fact, you should probably "cheat" and let GHC derive the Foldable
instance of your datatype for you automatically, using the DeriveFoldable
extension: 实际上,您应该“欺骗”并让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
(The relevant bits are the {-# LANGUAGE DeriveFoldable #-}
pragma at the top of your .hs file and the deriving (..., Foldable, ...)
clause in your datatype definition.) The fold
, foldMap
, etc. that come from the compiler-derived Btree
instance of Foldable
are almost certainly the ones you want anyway. (相关位是.hs文件顶部的
{-# LANGUAGE DeriveFoldable #-}
pragma和数据类型定义中的deriving (..., Foldable, ...)
子句。) fold
, foldMap
等来自Foldable
的编译器派生的Btree
实例几乎肯定是你想要的那些。 While you're at it, you might also want to derive Functor
and Traversable
instances, which is done exactly as for Foldable
. 当你在它的时候,你可能也想要派生
Functor
和Traversable
实例,这与Foldable
完全相同。 If you prefer, you can pass the DeriveXXX
pragmas via cabal or the command line, although I like the specificity of per-file pragmas. 如果您愿意,可以通过cabal或命令行传递
DeriveXXX
pragma,尽管我喜欢per-file pragma的特殊性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.