caesar_
caesar_

Reputation: 271

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.

Upvotes: 22

Views: 36365

Answers (3)

Will Ness
Will Ness

Reputation: 71065

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.

Upvotes: 14

daniel gratzer
daniel gratzer

Reputation: 53881

This code is almost right, you just need the correct indentation: Whitespace matters in haskell. Additionally, using an = after foo is an error with guards, so you'll have to remove that as well. The result is:

foo x
  | x == foo1 = 5
  | x == foo2 =3
  | x == foo3 =1
  | otherwise =2 
  where foo1= whatever1 x
        foo2= whatever2 x
        foo3= whatever3 x

Upvotes: 12

gspr
gspr

Reputation: 11227

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.

Upvotes: 38

Related Questions