Haskell `forever` type signature

人走茶凉 提交于 2019-12-23 07:29:34

问题


In Haskell why is type-signature of forever

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

Specifically why isn't it just :: Monad m => m a -> m a? Surely the type of monad we are acting upon doesn't change half way through forever?

A function such as:

 forever' :: Monad m => m a -> m a
 forever' = forever

seems to work exactly the same.


回答1:


The type signature of forever is crafted to suggest that its result runs forever. Specifically, there is no way to write an action of type m b (polymorphic in its return value) that terminates and yields a non-bottom value. An alternative way to suggest the same thing would be forever' :: m a -> m Void.

Another answer is to just say that this is the most general type available for the function as it's defined, so that's the one it was given.

Prelude> let forever m = let x = m >> x in x
Prelude> :t forever
forever :: Monad m => m a -> m b

These days, it probably should be defined differently:

forever :: Applicative f => f a -> f b
forever a = let x = a *> x in x


来源:https://stackoverflow.com/questions/30170279/haskell-forever-type-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!