Search code examples
haskellsyntaxparse-error

Beginner trouble with Haskell syntax


So I've only used Haskell for simple tutorials so far, and the below code is giving me a "parse error"...I know it's something to do with my syntax but I've no idea what

 --ternarySearch
  7 ternarySearch :: (Float -> Float) -> Float -> Float -> Float -> Float
  8 ternarySearch f a b tau = do 
  9                         if (abs(b-a) < tau)
 10                           then return ((a+b)/2)
 11                         c = (a + (b-a)/3)
 12                         d = (b - (b-a)/3)
 13                         if f(c) < f(d)
 14                           then return (ternarySearch f c b tau)
 15                         else return (ternarySearch f a d tau)

The error I'm getting is:

ternary.hs:11:25: parse error on input `c'

Any ideas?


Solution

  • You are doing lots of things wrong:

    • You should not use do-notation unless the context is a Monad.
    • Misuse of return: I think you are confusing imperative lanaguages return with Haskell's one.
    • if/else usage: Note that in Haskell if-else is an expression. So both if and else are mandatory as opposed to certain other languages.
    • Indendation seems to be wrong: See the rules here.

    A better version of what you are trying to do using guards:

    ternarySearch :: (Float -> Float) -> Float -> Float -> Float -> Float
    ternarySearch f a b tau 
        | abs (b-a) < tau = (a+b) / 2
        | f c < f d = ternarySearch f c b tau
        | otherwise = ternarySearch f a d tau
        where
          c = a + (b-a)/3
          d = b - (b-a)/3
    

    That being said, I would suggest you to read some book to get a better understanding.