哈斯克尔树木图 [英] Haskell Map for Trees

查看:81
本文介绍了哈斯克尔树木图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的树是由

data Tree a = Leaf a | Node (Tree a) (Tree a) 
        deriving (Show)

我还声明了一个测试树.

I also declare a testing tree.

myTree = Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)

我想要做的是创建一个函数maptree f,它将作用于Leaf.更具体地说,f x = x +1

What I want to do is create a function maptree f which will act on Leaf. To be more specifically, f x = x +1,

然后maptree f myTree将返回

Node (Node (Leaf 2) (Leaf 3)) (Leaf 4)

我的解决方法是

maptree f (Leaf a)= Leaf (f a)
maptree f (Node xl xr ) = Node (maptree xl) (maptree xr)

但是它将返回以下错误

Couldn't match expected type `Tree a'
       against inferred type `Tree t -> Tree t'
Probable cause: `maptree' is applied to too few arguments
In the first argument of `Node', namely `(maptree xl)'
In the expression: Node (maptree xl) (maptree xr)

失败,已加载模块:无.

Failed, modules loaded: none.

但是,如果我愿意

maptree (Leaf a)= Leaf ( a + 1)
maptree (Node xl xr ) = Node (maptree xl) (maptree xr)

确实可以解决.

我看不到第一个功能和第二个功能之间的区别.我如何得到错误?谢谢.

I can not see the difference between the first function and the second one. How do I get error? Thanks.

推荐答案

在更深层次地递归(对于这种高阶函数)时,不要忘记传递函数的一种愚蠢的方法是使用辅助函数:

One dumb way to not forget to pass along the function as you recurse deeper (for this sort of higher-order function) is to use a helper:

maptree f (Leaf a)     = Leaf (f a)
maptree f (Node xl xr) = Node (go xl) (go xr)
    where go = maptree f

或者(或者可能更常见):

Or, alternatively (and perhaps more commonly):

maptree f tree = go tree                      -- or eta reduce:   maptree f = go
    where go (Leaf a)     = Leaf (f a)
          go (Node xl xr) = Node (go xl) (go xr)

在第一个示例中,我将go用作maptree f的宏.在第二个示例中,我利用了maptree的输入fgo函数内部的范围内的事实,因为go是在maptreewhere子句中声明的.

In the first example, I use go sort of as a macro for maptree f. In the second example, I take advantage of the fact that maptree's input f is in scope inside the go function because go is declared in a where clause of maptree.

这篇关于哈斯克尔树木图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆