user2957781
user2957781

Reputation: 93

Haskell : unexpected ´;' possibly due to bad layout

I have to write an easy program telling me, how many solutions has a quadratic equation. I wrote:

howManySolutions :: Float -> Float -> Float -> Int

howManySolutions a b c = if (b^2-(4*a*c)) > 0 then 2 else 
                         if (b^2-(4*a*c)) == 0 then 1
                         else -1

but in WinHugs I get syntax error:

  unexpected ´;' possibly due to bad layout

I can open my program in GHCi, but it doesn't let me use negative numbers... What am i doing wrong?

Upvotes: 2

Views: 2091

Answers (3)

viorior
viorior

Reputation: 1803

Using -1 is a bad idea for Haskell. You could use Maybe a instead, like:

howManySolutions :: Float -> Float -> Float -> Maybe Int
howManySolutions a b c = let delta = b^2-(4*a*c) in
             if delta > 0 
             then Just 2 
             else if delta == 0 
                  then Just 1
                  else Nothing

Upvotes: 0

Alex Appetiti
Alex Appetiti

Reputation: 493

I'm not sure about the winhugs problem, but I can help you with the ghci one.

First of all, a bit of indentation:

howManySolutions a b c = if (b^2-(4*a*c)) > 0
                         then 2
                         else 
                           if (b^2-(4*a*c)) == 0
                           then 1
                           else -1

Now, if you try entering howManySolutions -1 2 3 into ghci, you get No instance for (Num (Float -> Float -> Float -> Int)) arising from a use of '-'. Basically it's interpreting '-' as a function to apply to 1 2 and 3 instead of just applying it to the '1'.

All you need to do is enter it as howManySolutions (-1) 2 3.

Now, if I can give you a tip, the way that patterns like this are usually handled are like so:

howManySolutions a b c
  | delta > 0 = 2
  | delta == 0 = 1
  | otherwise = -1
  where delta = b^2-4*a*c 

the '|' symbols (guards) act as different 'ifs', and the 'where' clause at the bottom let you define delta once to reuse multiple times in the guards. It's prettier :D

Upvotes: 7

epsilonhalbe
epsilonhalbe

Reputation: 15959

just use the right indentation

howManySolutions a b c = if (b^2-(4*a*c)) > 0 
                            then 2 
                            else if (b^2-(4*a*c)) == 0 
                                    then 1
                                    else (-1)

a more idiomatic solution would be

sol a b c | d >  0 = 2          
          | d <  0 = 0          
          | d == 0 = 1          
          where d = b^2-(4*a*c) 

Upvotes: 1

Related Questions