1

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!

2 Answers 2

4

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"
Sign up to request clarification or add additional context in comments.

Comments

4

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.