永远的monad如何工作? [英] How does forever monad work?
问题描述
永远的monad如何工作?
forever ::(Monad m)=> m a - > m b
forever a = a>>永远是
如果我写了
main = forever $ putStrLnSAD,我不明白!
永远获得IO(),这不是函数,怎么可以永远反复调用putStrLn? p>
从 forever
函数的定义,您可以看到它是一个标准的递归函数。
forever ::(Monad m)=> m a - > m b
forever a = a>>永远是一个
这里没有魔法。 forever
只是一个递归函数。在你的特定情况下,这是一个非终止的。但是它是否成为终止或非终止取决于Monad是如何为该类型定义的。
检查>>的类型
,我们得到:
λ> :t(>)
(>>):: Monad m => m a - > m b - > mb
您可以观察输入 ma
被忽略。另一种思考的方式是>>
函数仅执行传递给它的第一个参数的副作用。在你的情况下, ma
将对应于 IO()
,因为这是 putStrLn的类型
。
由于IO构成Monad,所以 forever
函数也可以作用于 IO
相关功能。
How does forever monad work?
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 IO (), this isn't function, how can forever repeatedly call putStrLn?
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.
这篇关于永远的monad如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!