Haskell 在do表示法中使用id

Haskell 在do表示法中使用id,haskell,monads,Haskell,Monads,我正在看哈斯克尔的在线课程《读者莫纳德》一章。讲师给出了以下示例: 此函数接受一个列表,如果列表为空或仅返回head,则不返回任何内容 安全头 -这里的论点是隐含的 实际上,你只是忘了报税。以下工作很好: safeHead' = do e <- id if (null e) then return Nothing -- need return here else return $ Just (head e) 为了获得更好的错误消息,请始终为顶级绑定

我正在看哈斯克尔的在线课程《读者莫纳德》一章。讲师给出了以下示例: 此函数接受一个列表,如果列表为空或仅返回head,则不返回任何内容

安全头 -这里的论点是隐含的
实际上,你只是忘了报税。以下工作很好:

safeHead' = do
  e <- id
  if (null e)
    then return Nothing         -- need return here
    else return $ Just (head e)

为了获得更好的错误消息,请始终为顶级绑定提供类型签名。在本例中,GHC发现了一个类型不匹配,并错误地将错误归咎于id,而实际上错误并没有。这是因为GHC没有足够的信息。
Prelude> :t null
null :: Foldable t => t a -> Bool
Prelude> :t id
id :: a -> a
safeHead' = do
  e <- id
  if (null e)
    then return Nothing         -- need return here
    else return $ Just (head e)
safeHead' = do
  e <- id
  return $ if (null e)
    then Nothing
    else Just (head e)