Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where Clause Applied To Multiple Patterns

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?

like image 613
BullyWiiPlaza Avatar asked Jan 15 '15 10:01

BullyWiiPlaza


1 Answers

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.

like image 76
András Kovács Avatar answered Sep 26 '22 03:09

András Kovács