1

I want to create Haskell function with different return value from its parameter, example: I want function isOdd 3 return value either True or False. I've tried

isOdd :: Integer -> Bool
isOdd x = (if x mod 2 == 0 False else True)

but it returns an error, can anybody help me? Also, is there a tutorial about functions in Haskell? I can't find a good tutorial about function in haskell.

1
  • 2
    if (pred) then ... else ... Commented Mar 6, 2013 at 16:41

2 Answers 2

14
isOdd :: Integer -> Bool
isOdd x = (if x mod 2 == 0 False else True)

You don't need the parens:

isOdd :: Integer -> Bool
isOdd x = if x mod 2 == 0 False else True

You missed out then:

isOdd :: Integer -> Bool
isOdd x = if x mod 2 == 0 then False else True

As you are using mod as an operator, you must surround it with backticks:

isOdd :: Integer -> Bool
isOdd x = if x `mod` 2 == 0 then False else True

That works.

Furthermore, you can write if blah then False else True more simply as not (blah):

isOdd :: Integer -> Bool
isOdd x = not (x `mod` 2 == 0)

Even more simply:

isOdd :: Integer -> Bool
isOdd x = x `mod` 2 /= 0

Please note: this is practically the same as the standard odd function.


Which tutorials have you tried?

Learn You A Haskell has a chapter introducing functions.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you :) i forget to add then in this question, and i dont really understand about importance backticks, difference between operator and function
3

The problem here is that mod isn't infix. Additionally, in Haskell if statements work like this

if cond then expr1 else expr2

Notice the then.

You should use mod like this mod x 2. However you can make it infix like this:

x `mod` 2

On a side not

x `mod` 2 /= 0

Is much easier to read than the whole if statement.


As far as tutorials: Learn You a Haskell for Great Good is a good start. For a more in depth coverage Real World Haskell is excellent.

If you just want to find a function then Hoogle is your friend.

3 Comments

thank you i just find that tutorial, i think i dont really understand concept in prefix and infix and importance of backticks
Prefix means before so func args the backticks are a special trick for functions with two arguments that let you write arg1 'func' arg2 just for clarity. There is no difference between mod x 2 and x 'mod' 2 except the second one is perhaps easier to understand
oh thx for the explanation :) how about class constraint? i didnt really get it

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.