Dictionary 使用foldTree实现Haskell映射树
这段代码来自我已经解决的作业。但我仍在试图弄清楚我是否可以修复我最初的尝试 我们得到了这个树结构和折叠树函数Dictionary 使用foldTree实现Haskell映射树,dictionary,haskell,tree,typeerror,Dictionary,Haskell,Tree,Typeerror,这段代码来自我已经解决的作业。但我仍在试图弄清楚我是否可以修复我最初的尝试 我们得到了这个树结构和折叠树函数 data Tree a = Leaf a | Node (Tree a) (Tree a) foldTree :: (b -> b -> b) -> (a -> b) -> Tree a -> b foldTree op f (Leaf x) = f x foldTree op f (Node l r) = foldTree op f l `o
data Tree a = Leaf a
| Node (Tree a) (Tree a)
foldTree :: (b -> b -> b) -> (a -> b) -> Tree a -> b
foldTree op f (Leaf x) = f x
foldTree op f (Node l r) = foldTree op f l `op` foldTree op f r
现在必须使用foldTree实现mapTree。
我是这样做的
mapTree :: (a -> b) -> Tree a -> Tree b
mapTree' f tree = foldTree Node (Leaf . f) tree
我最初想到但仍然没有开始工作的是:
mapTree :: (a -> b) -> Tree a -> Tree b
mapTree f tree = foldTree Node transFunc tree
where transFunc :: Tree a -> Tree b
transFunc (Leaf x) = Leaf (f x)
transFunc (Node l r) = Node (transFunc l) (transFunc r)
第二个函数是错误的,因为它的类型:
treea->treeb
,而foldTree
希望它是a->b
,其中a
取自树a
<mapTree
要求code>b为treeb
,因此foldTree
的第三个参数应为a->treeb
类型
因此,transFunc
最简单的固定版本是:
mapTree :: forall a b. (a -> b) -> Tree a -> Tree b
mapTree f tree = foldTree Node transFunc tree
where transFunc :: a -> Tree b
transFunc x = Leaf (f x)
请注意,您需要启用ScopedTypeVariables
扩展来编译它
这个版本的
transFunc
相当于您的工作解决方案:(Leaf.f)
您的初始实现应该修改为mapTree f tree=transFunc tree
,它除了不使用foldTree之外根本不起作用:/我不确定您在寻找什么样的答案。您已经给出了使用foldTree
@4castle的最合理的实现,也许OP想了解出了什么问题?如果您比较两个实现,或者只看foldTree
的类型签名,您会发现您的transFunc
应该具有类型签名a->treeb
。您应该能够从错误消息中看出这一点。