例如,给出以下树数据类型:
data Tree a = Node [Tree a] | Leaf a deriving Show
type Sexp = Tree String
如何使用高阶组合器表达“漂亮”功能,该组合使用适当的缩进打印树?例如:
sexp =
Node [
Leaf "aaa",
Leaf "bbb",
Node [
Leaf "ccc",
Leaf "ddd",
Node [
Leaf "eee",
Leaf "fff"],
Leaf "ggg",
Leaf "hhh"],
Leaf "jjj",
Leaf "kkk"]
pretty = ????
main = print $ pretty sexp
我希望该程序的结果是:
(aaa
bbb
(ccc
ddd
(eee
fff)
ggg
hhh)
jjj
kkk)
这是一个不完整的解决方案,使用“fold”作为组合器,不实现缩进:
fold f g (Node children) = f (map (fold f g) children)
fold f g (Leaf terminal) = g terminal
pretty = fold (\ x -> "(" ++ (foldr1 ((++) . (++ " ")) x) ++ ")") show
main = putStrLn $ pretty sexp
显然不可能使用fold
编写我想要的函数,因为它会忘记树结构。那么,什么是一个适当的高阶组合器,它足够通用,可以让我编写我想要的函数,但是比编写直接递归函数要强大?
答案 0 :(得分:15)
fold
足够强大;诀窍是我们需要将r
实例化为当前缩进级别的读者monad。
fold :: ([r] -> r) -> (a -> r) -> (Tree a -> r)
fold node leaf (Node children) = node (map (fold node leaf) children)
fold node leaf (Leaf terminal) = leaf terminal
pretty :: forall a . Show a => Tree a -> String
pretty tree = fold node leaf tree 0 where
node :: [Int -> String] -> Int -> String
node children level =
let childLines = map ($ level + 1) children
in unlines ([indent level "Node ["] ++ childLines ++ [indent level "]"])
leaf :: a -> Int -> String
leaf a level = indent level (show a)
indent :: Int -> String -> String -- two space indentation
indent n s = replicate (2 * n) ' ' ++ s
请注意,我将一个额外的参数传递给fold
的调用。这是缩进的初始状态,它起作用,因为r
的这种特化,fold
会返回一个函数。
答案 1 :(得分:4)
只是
onLast f xs = init xs ++ [f (last xs)]
pretty :: Sexp -> String
pretty = unlines . fold (node . concat) (:[]) where
node [] = [""]
node (x:xs) = ('(' : x) : map (" " ++) (onLast (++ ")") xs)