I wrote the following code. It is working and using the Reader
monad.
Could you give me some hints about code style in Haskell ? Mainly, I mean monads -
There's no need to go in and out of the Reader
the way you do it here by using runReader
; instead, you can rewrite it as
renumberR :: Tree a -> Reader Int (Tree Int)
renumberR (Node _ l r) = do
x <- ask
l' <- local (+1) (renumberR l)
r' <- local (+1) (renumberR r)
return (Node x l' r')
renumberR Empty = return Empty
However, you can write it even nicer by just using the applicative interface of Reader
:
renumberR (Node _ l r) =
Node <$> ask <*> local (+1) (renumberR l) <*> local (+1) (renumberR r)
renumberR Empty = pure Empty
Note that I have renamed your function to renumberR
to emphasize the fact that it runs in Reader
, but not necessarily using its monadic interface.