问题
I have a function with multiple patterns. I have two or more of them which share the same expression which I want to replace. Now if I write a where
clause at the bottom, indent it and define a new variable as the expression I wanted to replace it won't work.
Example:
myFunction firstParam secondParam = expression
myFunction firstParam _ = 1 + expression
where expression = firstParam + secondParam
Compiler message:
Not in scope: `expression'
Not in scope: `secondParam'
How do I do it?
回答1:
You can factor out the pattern matches into a case. For example:
myFunction :: Int -> Int -> Int
myFunction a b = case (a, b) of
(0, 4) -> x
(_, b) -> x + b
where
x = a + b
Here x
is visible in both case branches.
来源:https://stackoverflow.com/questions/27961795/where-clause-applied-to-multiple-patterns