1
votes

Reading the chapter on monads in real world Haskell. I came across the desugaring of the do notation, specifically when we have something like pattern <- action.

-- file: ch14/Do.hs
doNotation3 =
  do pattern <- act1
     act2
     {- ... etc. -}
     actN

The above example is desugared into:

-- file: ch14/Do.hs
translated3 =
  let f pattern = do act2
                   {- ... etc. -}
                   actN
      f _     = fail "..."
      in act1 >>= f

I am having trouble understanding is how you can have two pattern matching cases in a let clause?

I don't understand how you can have f pattern and f _ in the same let clause. I tried looking up if you can have multiple pattern matches in a let clause, but from what I have seen, most people use a case statement to do that.

I would like some help in understanding what is actually going on here?

1
with lambda-case it is equivalent to let f = (\case pattern -> do { act2; ... ; actN } ; _ -> fail "...") in act1 >>= f.Will Ness

1 Answers

3
votes

I am having trouble understanding is how you can have two pattern matching cases in a let clause?

Well, you can:

example :: Int -> Int
example n = 
  let f 0 = 1
      f x = x * f (x - 1)
  in  f n

Remember, that's a let … in… expression, not do's let. And for all bindings in such an expression, (almost) the same rules as for your usual top-level expressions hold, e.g. you can use pattern matching.

Maybe it gets a little bit easier if you transform it to where:

example :: Int -> Int
example n = f n
  where            
      f 0 = 1
      f x = x * f (x - 1)