How does the monad work forever?

How does the monad work forever?

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

If i write

main = forever $ putStrLn "SAD, I DON'T UNDERSTAND!"

forever gets the value of IO (), this is not a function, how can you call putStrLn permanently?

+4
source share
2 answers

From the function definition, foreveryou 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. foreveris only a recursive function. In your particular case, this does not end there. But whether it will be final or non-final depends on how Monad is defined for this type.

Inspect the type >>, we get:

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

, m a . , >> . m a IO (), putStrLn.

IO Monad, forever IO.

+7

, putStrLn "SAD, I DON'T UNDERSTAND!" , . . , - IO a, - a, IO. , - . , getCurrentTime time. IO UTCTime, , , .

+3

Source: https://habr.com/ru/post/1543244/


All Articles