【发布时间】:2020-02-04 15:51:23
【问题描述】:
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 来测试结果。现在所有元素都应该用大写字母书写。
我不知道如何使用递归来编写这个函数。
【问题讨论】:
-
提示:玫瑰树顶部的值应该如何处理,每个子树应该如何处理?
-
它应该首先更改玫瑰树顶部的元素,然后将相同的函数应用于其余元素,但我不知道如何将其转换为函数。跨度>
标签: haskell recursion tree map-function