我已经编写了编号树。如您所见,我使用了put
。可以在这里使用withState
吗?
renumberTree2Inorder :: Tree a -> StateT Int Identity (Tree Int)
renumberTree2Inorder Empty = return Empty
renumberTree2Inorder (Node _ l r) = (renumberTree2Inorder l) >>= (\l' ->
get >>= (\i -> put (i + 1) >>= (\_ -> renumberTree2Inorder r) >>= (\r' -> return (Node i l' r'))))
renumberTree2Inorder' :: Tree a -> Tree Int
renumberTree2Inorder' t = evalState (renumberTree2Inorder t) 0
答案 0 :(得分:1)
是。这是withState
的样子:
renumberTree2Inorder :: Tree a -> StateT Int Identity (Tree Int)
renumberTree2Inorder Empty =
return Empty
renumberTree2Inorder (Node _ l r) = do
l' <- renumberTree2Inorder l
i <- get
withState (+ 1) $ do
r' <- renumberTree2Inorder r
return (Node i l' r')
您仍然需要i <- get
,因此您可以在最后构建Node
。