Check if all arguments are different from each other

Viewed 141

I am a complete beginner at Haskell and got stuck at this. I want to write a function that returns True if all 3 arguments are different from each other and give False if they are similar.

threeArguments :: Int -> Int -> Int -> Bool
threeArguments a b c = if  a /= b && a /= c && b /= c 
    then return true 
    else return False

But I get error saying

• Couldn't match expected type ‘Bool’ with actual type ‘m0 a0’

enter image description here

2 Answers

The return function is not needed (in fact, you must not use it) here. It has a different meaning in Haskell than in most other languages -- presumably you will get to that bit of your tutorial a bit later.

threeArguments a b c = if a /= b && a /= c && b /= c
    then True
    else False

(I assume the true instead of True in your question was just a transcription error.)

As an aside, the if foo then True else False is a really common beginner antipattern. Just use foo instead.

threeArguments a b c = a /= b && a /= c && b /= c

And, just for fun, there are other ways of implementing this. For example, you might like

threeArguments a b c = nub [a,b,c] == [a,b,c]

for its brevity and easy generalization to additional arguments.

return is a function in Haskell, part of Monad (documentation). It’s not used any time you need to define a function’s value like it would be in some other languages. If you wanted your function to always produce True, for example, you would write it like this:

threeArguments :: Int -> Int -> Int -> Bool
threeArguments a b c = True

True is a Bool value, and there’s no return involved. Likewise, the form of if is if condition then trueValue else falseValue, where condition is a Bool and the overall if expression has the same type as trueValue and falseValue, so you’re looking for:

threeArguments :: Int -> Int -> Int -> Bool
threeArguments a b c = if a /= b && a /= c && b /= c 
    then True 
    else False

But if condition then True else False is redundant, because it has the same value as condition.

threeArguments :: Int -> Int -> Int -> Bool
threeArguments a b c = a /= b && a /= c && b /= c
Related