How does forever monad work?

后端 未结 2 972
天涯浪人
天涯浪人 2021-01-12 10:48

How does forever monad work?

forever :: (Monad m) => m a -> m b
forever a = a >> forever a

If I write

main =          


        
2条回答
  •  -上瘾入骨i
    2021-01-12 11:14

    From the definition of forever function, you can see that it is a standard recursive function.

    forever :: (Monad m) => m a -> m b
    forever a = a >> forever a
    

    There is no magic going on there. forever is just a recursive function. In your particular case, this is a non terminating one. But whether it becomes a terminating or non terminating depends on how the Monad is defined for that type.

    Inspect the type of >>, we get:

    λ> :t (>>)
    (>>) :: Monad m => m a -> m b -> m b
    

    From that you can observe the input m a is just ignored. Another way to think about that is that >> function just performs the side effect of the first parameter passed to it. In your case the m a will correspond to IO () since that is the type of putStrLn.

    Since IO forms a Monad, forever function can also act on IO related functions.

提交回复
热议问题