Haskell - depth for each node in binary tree using Reader monad

后端 未结 2 507
臣服心动
臣服心动 2020-12-02 01:58

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 -

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 02:52

    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.

提交回复
热议问题