在 haskell 中按深度优先顺序标记树

Labeling a tree depth-first in-order in haskell

我的问题基本上与此处提出的问题相同:Haskell label a binary tree through depht-first in-order traversel 但实际上从未给出答案,由于缺乏声誉,我无法在那里发表评论。

现在我有一个函数label:

label :: MonadState m Int => Tree a -> m (Tree (Int, a))
label Leaf = return Leaf
label (Branch leftTree a rightTree) = do n <- get
                                         modify (+1)      
                                         l' <- label leftTree
                                         r' <- label rightTree
                                         return (Branch l' (n,a) r')

其中 Tree a = Leaf | Branch (Tree a) a (Tree a).

现在这标记树广度优先。现在我想先标记 leftTree,然后是 Branch 本身,然后是 rightTree,但我不知道如何实现这一点,另一个线程也没有进一步帮助我.

我刚刚回答了较旧的问题 here。抱歉错误地归因于你。关键是,当您编写类型时,您还告诉 Haskell 如何 traverse 您的数据结构,以确保 get 发生在中间。

你自己本地写错的程序是你定义类型就写对的程序,你要是知道就好了。