简体   繁体   English

Haskell - 树的fmap和foldMap

[英]Haskell - fmap and foldMap for Tree

im new to haskell and im a bit stuck i have 我是新的哈斯克尔,我有点卡住了我

data Tree a = Empty | Leaf a | Branch a (Tree a) (Tree a)
    deriving (Show)

I want to crate an fmap and a foldMap , so i tried 我想创建一个fmap和一个foldMap,所以我试过了

instance Functor Tree where
    fmap f (Leaf x) = Leaf (f x)
    fmap f (Branch a left right) = Branch a (fmap f left) (fmap f right)

and it simply doesn't work and i don't understand why , i'm pretty sure the problem is here 它根本不起作用,我不明白为什么,我很确定问题就在这里

.. = Branch a (fmap f left) (fmap f right)

anyway i could really use some help for the fmap and foldMap ,actually i have an idea but i don't have the right syntax. 无论如何,我真的可以使用fmap和foldMap的一些帮助,实际上我有一个想法,但我没有正确的语法。

thanks for the help. 谢谢您的帮助。

You are forgetting to apply the function f on the a s contained in the Branch nodes as well, otherwise you only apply the function on the leaves. 您忘记在Branch节点中包含a s上应用函数f ,否则您只在叶子上应用函数。 Moreover, you are forgetting a case for the Empty constructor. 而且,您忘记了Empty构造函数的情况。

instance Functor Tree where
  fmap f Empty = Empty
  fmap f (Leaf x) = Leaf (f x)
  fmap f (Branch a left right) = Branch (f a) (fmap f left) (fmap f right)

As an aside, I think that your data declaration maybe isn't quite right (or rather is not standard). 顺便说一句,我认为您的数据声明可能不太正确(或者说不是标准的)。 Typically one defines 通常一个人定义

data Tree a = Nil | Node a (Tree a) (Tree a)

That is, a Tree is either an empty node ( Nil ), or a Node that contains a value and two subtrees. 也就是说, Tree是空节点( Nil ),或者是包含值和两个子树的Node In this way, you can represent a nonempty tree with no branches as Node a Nil Nil . 通过这种方式,您可以将没有分支的非空树表示为Node a Nil Nil

Anyway, to properly define the Functor instance for this type (the instance for your Tree type is similar), you need to define fmap :: (a -> b) -> Tree a -> Tree b for the all the possible values of type Tree a -- in this case, the empty value and the nonempty value. 无论如何,要正确定义此类型的Functor实例( Tree类型的实例类似),您需要定义fmap :: (a -> b) -> Tree a -> Tree b以获取所有可能的值输入Tree a - 在这种情况下,为空值和非空值。 You're on the right track with your implementation, but you forgot to apply f to the value contained in the nonempty node: 您的实现正处于正确的轨道上,但是您忘记将f应用于非空节点中包含的值:

instance Functor Tree where
  fmap _ Nil = Nil -- nothing to fmap in this case
  fmap f (Node a left right) = Node (f a) (fmap f left) (fmap f right)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM