简体   繁体   中英

Pattern-matching in case, Haskell

I'm fairly new to Haskell and have a question about pattern-matching. 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. 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? 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 ; otherwise the second alternative will be executed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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