简体   繁体   English

模式匹配,Haskell

[英]Pattern-matching in case, Haskell

I'm fairly new to Haskell and have a question about pattern-matching. 我对Haskell并不陌生,并且对模式匹配有疑问。 Here is a heavily simplified version of the code: 这是代码的简化版本:

data Value = MyBool Bool | MyInt Integer

codeDuplicate1 :: Value -> Value -> IO Value
codeDuplicate1 = generalFunction True 

codeDuplicate2 :: Value -> Value -> IO Value
codeDuplicate2 = generalFunction False 

generalFunction :: Bool -> Value -> Value -> IO Value
generalFunction b x1 x2 = do result <- eval x1 
                             case result of
                               MyBool b -> do putStrLn $ show b
                                              return (MyBool b)   
                               _        -> eval x2

eval :: Value -> IO Value
eval (MyInt x) | x > 10    = return (MyInt 10)
               | x > 5 = return (MyBool True)
               | otherwise = return (MyBool False)

Now, I realize that the argument b in generalFunction is not the same as the b in the case part, and therefore, this code will print b regardless of the input. 现在,我意识到generalFunction中的参数b与case部分中的b不同,因此,无论输入内容如何,​​此代码都将输出b。 I used the same name just to show my intentions. 我使用相同的名字只是为了表达我的意图。 So my question is: 所以我的问题是:

Is there a way to match the first b with the second, so that if the bs are the same it will print, otherwise it will evaluate x2? 有没有办法将第一个b与第二个b匹配,以便如果b相同,它将打印,否则它将评估x2? And, if there isn't, is there another good way to get the intended result? 而且,如果没有,还有另一种好的方法来获得预期的结果吗?

I almost found the answer in this question , but I think this situation is slightly different. 我几乎找到了这个问题的答案,但我认为这种情况略有不同。

You can use a guarded pattern. 您可以使用保护模式。 The first alternative will be executed if MyBool is matched and b == b2 ; 如果MyBool被匹配并且 b == b2 ,则将执行第一个选择; otherwise the second alternative will be executed. 否则将执行第二种选择。

case result of
  MyBool b2 | b == b2 -> do {print b; return $ MyBool b}
  _ -> eval x2

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

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