data RoseTree a = RoseNode a [RoseTree a] deriving Show
things :: RoseTree String
things =
RoseNode "thing" [
RoseNode "animal" [
RoseNode "cat" [], RoseNode "dog" []
],
RoseNode "metal" [
RoseNode "alloy" [
RoseNode "steel" [], RoseNode "bronze" []
],
RoseNode "element" [
RoseNode "gold" [], RoseNode "tin" [], RoseNode "iron" []
]
],
]
-- Turns string into all upper case
allCaps :: String -> String
allCaps x = map toUpper x
-- This function uses allCaps as a helper function
-- to turn the elements in tree into upper case
roseMap :: (a -> b) -> RoseTree a -> RoseTree b
roseMap f rtree = case rtree of
RoseNode a [] -> allCaps a
RoseNode a sub -> Rose (allCaps a) (map (roseMap f sub)
这需要一个函数,并将其应用于玫瑰树的每个元素。通过将函数allCaps
映射到玫瑰树things
来测试结果。所有元素现在都应该以大写形式编写。
我不知道如何使用递归来编写这个函数。
你已经在使用递归了。事实上,你使用roseMap f
本身:
roseMap :: (a -> b) -> RoseTree a -> RoseTree b
roseMap frtree = case rtree of
RoseNode a [] ->allCaps a
RoseNode a sub ->Rose (allCaps a) (map (roseMap fsub))
但是由于以下几个原因,上述方法不起作用:
- 您在此处不使用
f
。事实上,你写Rose (allCaps a)
,所以你不使用f
来映射元素; sub
不应在roseMap f
的括号中传递;- 你应该使用
RoseNode
而不是Rose
;和 - 您的第一种情况,您返回
allCaps a
,而不是RoseNode (allCaps a) []
。
区分没有子节点或有子节点的节点是没有必要的。我们可以将映射定义为:
roseMap :: (a -> b) -> RoseTree a -> RoseTree b
roseMap f (RoseNode a xs) = RoseNode (f a) (map (roseMap f) xs)
所以这里我们改用f a
,并对子项执行映射。
如果我们然后执行一个以allCaps
作为函数的roseMap
,我们得到:
Prelude Data.Char> roseMap allCaps things
RoseNode "THING" [RoseNode "ANIMAL" [RoseNode "CAT" [],RoseNode "DOG" []],RoseNode "METAL" [RoseNode "ALLOY" [RoseNode "STEEL" [],RoseNode "BRONZE" []],RoseNode "ELEMENT" [RoseNode "GOLD" [],RoseNode "TIN" [],RoseNode "IRON" []]],RoseNode "FRUIT" [RoseNode "APPLE" [RoseNode "GRANNY SMITH" [],RoseNode "PINK LADY" []],RoseNode "BANANA" [],RoseNode "ORANGE" []],RoseNode "ASTRONOMICAL OBJECT" [RoseNode "PLANET" [RoseNode "EARTH" [],RoseNode "MARS" []],RoseNode "STAR" [RoseNode "THE SUN" [],RoseNode "SIRIUS" []],RoseNode "GALAXY" [RoseNode "MILKY WAY" []]]]
我们不需要自己实现映射,我们可以启用DeriveFunctor
扩展 [ghc-doc],让 Haskell 为我们完成工作:
{-# LANGUAGEDeriveFunctor#-}
data RoseTree a = RoseNode a [RoseTree a] deriving (Functor, Show)
我们可以用fmap :: Functor f => (a -> b) -> f a -> f b
来称呼它:
Prelude Data.Char> fmap (map toUpper) things
RoseNode "THING" [RoseNode "ANIMAL" [RoseNode "CAT" [],RoseNode "DOG" []],RoseNode "METAL" [RoseNode "ALLOY" [RoseNode "STEEL" [],RoseNode "BRONZE" []],RoseNode "ELEMENT" [RoseNode "GOLD" [],RoseNode "TIN" [],RoseNode "IRON" []]],RoseNode "FRUIT" [RoseNode "APPLE" [RoseNode "GRANNY SMITH" [],RoseNode "PINK LADY" []],RoseNode "BANANA" [],RoseNode "ORANGE" []],RoseNode "ASTRONOMICAL OBJECT" [RoseNode "PLANET" [RoseNode "EARTH" [],RoseNode "MARS" []],RoseNode "STAR" [RoseNode "THE SUN" [],RoseNode "SIRIUS" []],RoseNode "GALAXY" [RoseNode "MILKY WAY" []]]]