let-syntax in pattern [GHC-78892]
Pattern matching allows constructors and literals to be used to take apart values, exposing their contents. Even though patterns resemble expressions, they are not evaluated. The let ... in ...
syntax is used to introduce declarations that are scoped to an expression, which doesn’t make sense as a pattern without evaluation. See GHC-04584 for more information on why expressions aren’t permitted in pattern matching.
## Example Text
(let ... in ...)-syntax in pattern
Examples
Using let ... in ... syntax in pattern.
When pattern matching, let expressions are not allowed as patterns to be matched against. The logic encapsulated here should either be lifted to outside of the function, or moved inside of the function itself.
Error Message
Example.hs:5:6: error: [GHC-78892]
(let ... in ...)-syntax in pattern
|
5 | f n (let exp = x^2 in exp n) = True
| ^^^^^^^^^^^^^^^^^^^^^^
# Intermediate fix step In the below example, it is worth noting that you may first have considered refactoring to something along the lines of
sq :: Int -> Int
sq x = x^2
f :: Int -> Int -> Bool
f n (sq n) = True
f n _ = False
The above code would throw a parse error in the pattern GHC-07626.
Example.hs
module Example where
-- Is the second argument the square of the first?
f :: Int -> Int -> Bool
f n (let sq = x^2 in sq n) = True
f n _ = False
module Example where
-- Is the second argument the square of the first?
sq :: Int -> Int
sq x = x^2
f :: Int -> Int -> Bool
f n m
| m == sq n = True
| otherwise = False