haskell - 使用withState代替put

时间:2016-04-12 17:00:20

标签: haskell monads

我已经编写了编号树。如您所见,我使用了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

1 个答案:

答案 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