anonymous
anonymous

Reputation: 313

parse error on input ‘if’ in Haskell code

I'm trying to use Haskell and I am new to this programming language. I was running this code which was intended to print Greater when the function had an integer greater than 50 and Less when the function was run with an integer less than 50.

printLessorGreater :: Int -> String
    if a > 50
        then return ("Greater") 
        else return ("Less")
    
main = do
    print(printLessorGreater 10)

However, when I ran the code, it gave me this error:

main.hs:2:5: error: parse error on input ‘if’

I went to line 5 and there was nothing in the line. Does anyone know how to solve this error at this point? I would appreciate it!

Upvotes: 1

Views: 194

Answers (2)

chi
chi

Reputation: 116139

You probably want something like this:

printLessorGreater :: Int -> String
printLessorGreater a = if a > 50
   then "Greater"
   else "Less"

Note that this does not actually print anything, but only returns a string.

Using an if is fine for this, but note that guards are also a common alternative.

printLessorGreater :: Int -> String
printLessorGreater a | a > 50    = "Greater"
                     | otherwise = "Less"

Upvotes: 4

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

your function clause has no "head". You need to specify the name of the function and with optional patterns:

printLessorGreater :: Int -> String
printLessorGreater a = if a > 50 then return ("Greater") else return ("Less")

but this will still not work. Thre return is not equivalent to the return statement in imperative languages. return :: Monad m => a -> m a injects a value in a monadic type. While a list is a monadic type, if you use the list monad, you can only use return with a Character in that case.

You thus should rewrite this to:

printLessorGreater :: Int -> String
printLessorGreater a = if a > 50 then "Greater" else "Less"

or with a guard:

printLessorGreater :: Int -> String
printLessorGreater a
    | a > 50 = "Greater"
    | otherwise = "Less"

Upvotes: 4

Related Questions