简体   繁体   English

如何在 Haskell 的 case 语句中添加多行?

[英]How to have multiply lines in a case statement in Haskell?

I'm coding in Haskell for the first time, and I'm having trouble with case statements.我是第一次在 Haskell 中编码,我在处理 case 语句时遇到了问题。

points = do
  pts <- try(readLn :: IO Int) :: IO (Either SomeException Int)
  case pts of
    Left ex -> putStrLn "Please enter a number."
    Right val -> return pts

This code is for reading an integer from user input, and checking to make sure it is indeed an int.此代码用于从用户输入中读取 integer,并检查以确保它确实是一个 int。 The issue I'm having is with the Left ex case.我遇到的问题是Left ex案例。 What I want to do is, if there's an exception, to print the line "Please enter a number."我想做的是,如果有异常,打印"Please enter a number." and then run the points function again.然后再次运行点function。 The issue is that I can't figure out how to call points within the Left ex case, as it interferes with the print statement.问题是我无法弄清楚如何在Left ex案例中调用点,因为它会干扰打印语句。 Any guidance?任何指导?

You can use the do notation, which allows to glue several IO (or another monad's) actions in order, like you're already doing in the body of points itself:您可以使用do表示法,它允许按顺序粘合多个IO (或另一个 monad 的)操作,就像您已经在points本身中所做的那样:

points = do
  pts <- try(readLn :: IO Int) :: IO (Either SomeException Int)
  case pts of
    Left ex -> do
      putStrLn "Please enter a number."
      points
    Right val -> return pts

Alternatively, you could do what the do notation does under the hood, and use the >>= operator, which is what glues two IO actions in order:或者,您可以执行do表示法在后台执行的操作,并使用>>=运算符,这就是按顺序粘合两个IO操作的原因:

points = do
  pts <- try(readLn :: IO Int) :: IO (Either SomeException Int)
  case pts of
    Left ex -> putStrLn "Please enter a number." >>= \_ -> points
    Right val -> return pts

Note that the \_ -> bit ignores the first action's return value.请注意, \_ ->位会忽略第一个操作的返回值。 So you can use the >> operator, which does the same thing as >>= , but throws away the first action's result:因此,您可以使用>>运算符,它的作用与>>=相同,但会丢弃第一个操作的结果:

points = do
  pts <- try(readLn :: IO Int) :: IO (Either SomeException Int)
  case pts of
    Left ex -> putStrLn "Please enter a number." >> points
    Right val -> return pts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM