Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
二叉树上的FOLD在haskell中的应用_Haskell_Functional Programming_Binary Tree - Fatal编程技术网

二叉树上的FOLD在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) 但我得到了编译错误-

我有一个实现二叉树的小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)
但我得到了编译错误-

 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)