Haskell - guard inside case statement

前端 未结 1 674
花落未央
花落未央 2021-02-05 04:18

I am going through Learn you a haskell book, and in Chapter 8 there is a snippet of code which looks like this

data LockerState = Taken | Free deriving (Eq, Show         


        
相关标签:
1条回答
  • 2021-02-05 04:55

    There are two places guards are allowed: function definitions and case expressions. In both contexts, guards appear after a pattern and before the body, so you use = in functions and -> in case branches, as usual:

    divide x y
      | y == 0 = Nothing
      --------
      | otherwise = Just (x / y)
      -----------
    
    positively mx = case mx of
      Just x | x > 0 -> Just x
             -------
      _ -> Nothing
    

    Guards are simply constraints for patterns, so Just x matches any non-Nothing value, but Just x | x > 0 only matches a Just whose wrapped value is also positive.

    I suppose the definitive reference is the Haskell Report, specifically §3.13 Case Expressions and §4.4.3 Function and Pattern Bindings, which describe the syntax of guards and specify where they’re allowed.

    In your code, you want:

    Just (state, code)
      | state == Taken -> Left "LockerNumber already taken!"
      | otherwise -> Right code
    

    This is also expressible with patterns alone:

    Just (Taken, _) -> Left "LockerNumber already taken!"
    Just (_, code) -> Right code
    
    0 讨论(0)
提交回复
热议问题