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.
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.
The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With