gpt4 book ai didi

树的 Haskell map

转载 作者:行者123 更新时间:2023-12-04 13:02:01 25 4
gpt4 key购买 nike

我的树由

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

我还声明了一个测试树。
myTree = Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)

我想要做的是创建一个函数 maptree f 它将作用于 Leaf。更具体地说, 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)

失败,加载模块:无。

但是,如果我这样做
maptree (Leaf a)= Leaf ( a + 1)
maptree (Node xl xr ) = Node (maptree xl) (maptree xr)

它确实有效。

我看不出第一个函数和第二个函数之间的区别。我如何得到错误?谢谢。

最佳答案

您缺少递归 maptree 调用中的函数:

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

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

关于树的 Haskell map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7624774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com