Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any way for multiple where statement in Haskell

i tried to write 3-4 where statement in a one function but i get error and couldnt do it , i tried to do something like that :

foo x=
| x == foo1 = 5
| x == foo2 =3
| x == foo3 =1
| otherwise =2 
where foo1= samplefunct1 x
      foo2= samplefunct2 x
      foo3= samplefunct3 x

I know the code is a bit useless but i just wrote this to give an example about what i mean.

Is there anyone who can help me ? Thanks in advance.

like image 558
caesar_ Avatar asked Apr 01 '13 09:04

caesar_


People also ask

How does where work in Haskell?

Definition on Haskell Where Function. Haskell where is not a function rather it is a keyword that is used to divide the more complex logic or calculation into smaller parts, which makes the logic or calculation easy to understand and handle.

What does ++ mean in Haskell?

The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list.

Does Haskell have Elif?

Note that Haskell does not have an "elif" statement like Python. You can still achieve this effect though! You can use an if-statement as the entire expression for an else-branch.

What does let do in Haskell?

Let bindings let you bind to variables anywhere and are expressions themselves, but are very local, so they don't span across guards. Just like any construct in Haskell that is used to bind values to names, let bindings can be used for pattern matching.


2 Answers

Remove the = after foo x and indent your code like

foo x     | x == foo1 = 5     | x == foo2 =3     | x == foo3 =1     | otherwise =2      where foo1 = samplefunct1 x           foo2 = samplefunct2 x           foo3 = samplefunct3 x 

and you're fine.

like image 163
gspr Avatar answered Sep 18 '22 09:09

gspr


If your indentation is a bit uneven, like this:

foo x
 | x == foo1 = 5
 | x == foo2 =3
 | x == foo3 =1
 | otherwise =2 
 where foo1= samplefunct1 x
        foo2= samplefunct2 x
         foo3= samplefunct3 x

then indeed, the error message talks about unexpected = (and in the future, please do include full error message in the question body).

You fix this error by re-aligning, or with explicit separators { ; }, making it white-space–insensitive:

foo x
 | x == foo1 = 5
 | x == foo2 =3
 | x == foo3 =1
 | otherwise =2 
 where { foo1= samplefunct1 x ;
        foo2= samplefunct2 x ;
          foo3= samplefunct3 x }

This runs fine (not that it is a nice style to use). Sometimes it even looks even to you, but isn't, if there are some tab characters hiding in the white-space.

like image 24
Will Ness Avatar answered Sep 17 '22 09:09

Will Ness