case on monadic value

最后都变了- 提交于 2020-06-09 11:04:26

问题


Is there a way to perform a case on the value stored within a monad without having to bind a name to it?

i.e. instead of doing this:

c <- getChar
case c of
  ...

Is there a way to do this:

mcase getChar of
  ...

Alternatively, it would be nice if the case statement could be partially applied so:

case of
  ...

would be desugared to:

\a -> case a of
  ...

So you could do this:

getChar >>= case of
              ...

回答1:


The answer is no. In Haskell 98, you can't use a case statement without using a name inside it. But there is a proposal for adding support for case-lambdas. The syntax they propose is the same you propose too.




回答2:


The proposal mentioned by FUZxxl was now implemented in GHC since 7.6.1, it's called LambdaCase.

Now you can do:

{-# LANGUAGE LambdaCase #-}
getChar >>= \case
   ...

Note the \ before the case keyword and the fact that there is no of in that case.




回答3:


No, not really, but you can move the case into another function and apply it to the result of a monadic action.

f x = case  x of ...

main = do
  f <$> getChar

Alternativly, the following is possible:

getChar >>= \x -> case x of ...


来源:https://stackoverflow.com/questions/5395517/case-on-monadic-value

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