Is Haskell's mapM not lazy?

前端 未结 5 783
情歌与酒
情歌与酒 2020-12-01 23:36

UPDATE: Okay this question becomes potentially very straightforward.

q <- mapM return [1..]

Why does this never return

5条回答
  •  一个人的身影
    2020-12-01 23:59

    Okay this question becomes potentially very straightforward.

    q <- mapM return [1..]

    Why does this never return?

    It's not necessarily true. It depends on the monad you're in.

    For example, with the identity monad, you can use the result lazily and it terminates fine:

    newtype Identity a = Identity a
    
    instance Monad Identity where
      Identity x >>= k = k x
      return = Identity
    
    -- "foo" is the infinite list of all the positive integers
    foo :: [Integer]
    Identity foo = do
      q <- mapM return [1..]
      return q
    
    main :: IO ()
    main = print $ take 20 foo -- [1 .. 20]
    

提交回复
热议问题