简体   繁体   English

模式匹配功能结果

[英]Pattern match on function result

I am trying to do match on function result on scala it will look like this 我正在尝试在scala上对功能结果进行匹配,它将看起来像这样

validate(number) match {
case true => "true"
case false => "false"
}

I am trying to do something similar in haskell 我正在尝试在Haskell中做类似的事情

main = do    
    number <- getLine  
    res <- case (validate (read number::Int)) of 
        (True) -> "True"
        (False) -> "False"
    putStrLn res

Also I understand I can do with out the do notation, but not sure where to start. 我也知道我可以不用do符号,但是不确定从哪里开始。

In Haskell read throws an exception if there is a parse error. 在Haskell中,如果存在解析错误,则read引发异常。

But there is readMaybe which will return a Maybe value. 但是有readMaybe将返回Maybe值。

import Text.Read

main = do
  number <- getLine
  let res = case (readMaybe number :: Maybe Int) of
              Just x -> "True"
              Nothing -> "False"
  putStrLn res

Note the use of let instead of monadic bind operator <- since readMaybe is a pure function. 请注意使用let代替单子绑定运算符<-因为readMaybe是一个纯函数。

You might even be able to avoid the type hint if you use the parsed value in a way which allows the compiler to infer its type, eg: 如果以允许编译器推断其类型的方式使用解析后的值,则甚至可以避免类型提示,例如:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
  -- any list will do

main = do
  number <- getLine
  case readMaybe number of
    Nothing -> putStrLn "bad number"
    Just n  -> print (fibs !! n)

No type annotation is needed here because !! 这里不需要类型注释,因为!! take an Int argument, and so n must have type Int which means readMaybe number must have type Maybe Int . 接受一个Int参数,因此n必须具有Int类型,这意味着readMaybe number必须具有Maybe Int类型。

Update 更新

Stylistically I would recommend that you use let here - using bind is completely unnecessary as you are computing a pure value. 从风格上我会建议你使用let在这里-使用绑定是完全不必要的,因为你是计算一个纯粹的价值。

However, you can write this with the bind operator by using return : 但是,您可以使用return运算符使用bind运算符编写此代码:

main = do
  number <- getLine
  res <- return $ case (readMaybe number :: Maybe Int) of
                    Just _ -> "True"
                    Nothing -> "False"
  putStrLn res

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

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