[英]Haskell - Mapping a function over a Rose Tree
If I define a Rose tree as 如果我将玫瑰树定义为
data RTree = Node a [RTree a]
deriving(Show, Eq)
How would I go about defining a map function for it? 我该如何为它定义地图功能? The map function is to be defined as
map函数定义为
map_rose_tree :: (a -> b) -> RTree a -> RTree b
The easiest way is to enable the DeriveFunctor
extension and derive Functor
: 最简单的方法是启用
DeriveFunctor
扩展并derive Functor
:
{-# LANGUAGE DeriveFunctor #-}
data RTree a
= Node a [RTree a]
deriving (Show, Eq, Functor)
map_rose_tree = fmap
But if you wanted to define the instance yourself you'll need to pattern match on the RTree
constructor: 但是如果你想自己定义实例,你需要在
RTree
构造函数上进行模式匹配:
instance Functor RTree where
fmap f (Node a children) = Node _ _
You'll have to fill in the two _
yourself. 你必须自己填写两个
_
。 If you have a new enough version of GHC, you can compile this and get errors telling you the types of the holes ( _
) along with relevant bindings that you can use to implement it. 如果你有一个足够新的GHC版本,你可以编译它并得到错误,告诉你洞的类型(
_
)以及你可以用来实现它的相关绑定。 The first hole is pretty easy, the second one is a little more challenging, but I assure you it can be solved with only fmap
, f
, a
, and children
. 第一个洞非常简单,第二个洞更具挑战性,但我向你保证只有
fmap
, f
, a
和children
才能解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.