简体   繁体   English

自定义n元树的映射功能

[英]Map function for custom n-ary tree

I'm trying to get a mapping function like this working for an n-ary tree, but am struggling. 我正在尝试让像这样的映射函数适用于n元树,但是很费劲。

data NTree a = Leaf a | Node a [NTree a]

ntreeMap :: (a -> b) -> NTree a -> NTree b
ntreeMap f (Leaf x) = Leaf (f x)
ntreeMap f (Node y t) = Node (ntreeMap f y) (ntreeMap f t)

gives me 给我

Type error in application
*** Expression     : ntreeMap f t
*** Term           : t
*** Type           : [NTree b]
*** Does not match : NTree a

Could someone give me a pointer as to where I'm going wrong? 有人可以给我指出我要去哪里的地方吗? Thanks 谢谢

You have two problems here. 您在这里有两个问题。 One is that you need not invoke ntreeMap recursively for y in the Node case as it is of type a and not NTree a : 一个是您不必在Node情况下递归调用y ntreeMap ,因为它的类型为a而不是NTree a

ntreeMap f (Node y t) = Node (f y) (ntreeMap f t)

The second one is that t is a list of trees and your function only maps over a single tree, so it should be 第二个是t是树的列表,您的函数仅映射一棵树,因此应该

ntreeMap f (Node y t) = Node (f y) (map (ntreeMap f) t)

BTW: Your type is a Functor. 顺便说一句:您的类型是函子。

An interesting thing about Functors is that there's only one way for a type to be a Functor (and adhering to the Functor laws). 关于函子的一个有趣的事情是,只有一种方式可以使函子成为函子(并遵守函子定律)。

Therefore Functor instances can be automatically derived: 因此,可以自动派生Functor实例:

{-# LANGUAGE TemplateHaskell #-}

import Data.DeriveTH

data NTree a = Leaf a | Node a [NTree a]
$( derive makeFunctor ''NTree )

ntreeMap :: (a -> b) -> NTree a -> NTree b
ntreeMap = fmap

While I think Rüdiger's answer is the best one I just wanted to add that in GHC 6.12 you can automatically derive a Functor instance for your datatype: 尽管我认为Rüdiger的答案是最好的,但我只是想补充一点,在GHC 6.12中,您可以自动为您的数据类型派生Functor实例:

{-# LANGUAGE -DeriveFunctor #-}
data NTree a = Leaf a | Node a [NTree a]
  deriving Functor

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

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