Reputation: 105
So i have this function
intCMP :: Int -> Int -> Ordering
intCMP a b | a == b =EQ
| a < b = LT
| otherwise = GT
and this list defined
xs = [1,2,3]
I'm trying to find information about the list but I'm having troouble passing elements into intCMP
This is what I'm trying to do
intCMP head(xs) 1
But this give me and error saying it has too many arguements.
<interactive>:2:9: error:
• Couldn't match expected type ‘Int’ with actual type ‘Integer’
• In the first argument of ‘intCMP’, namely ‘(head xs)’
In the expression: intCMP (head xs) 1
In an equation for ‘it’: it = intCMP (head xs) 1
Upvotes: 1
Views: 123
Reputation: 925
The error is not about having too many arguments, it's about the type of your list elements being Integer
instead of the expected Int
.
You have two choices here:
First: Make your function more general by allowing all Ord
(Orderable) types to be accepted (note that this function is available in Prelude as compare
)
intCMP :: (Ord a) => a -> a -> Ordering
intCMP a b | a == b =EQ
| a < b = LT
| otherwise = GT
Second, cast your list element's type to the one required using fromIntegral
:
intCMP (fromIntegral $ head intxs) 1
Upvotes: 2
Reputation: 233197
In Haskell, functions are called by typing the name of the function, followed by each argument. The arguments are separated by space.
In other languages, particularly the descendants of C, you call methods by passing arguments in brackets, but not in Haskell. The brackets don't indicate a function call, they're used entirely to modify the normal operator precedence.
It's like in basic arithmetic, where you have a normal order of operator precedence. For example, 1 + 2 * 3
is the same as 1 + (2 * 3)
, so you normally don't write the latter. If, however, you wish to evaluate the addition before the multiplication, you use brackets to indicate a deviation from the norm: (1 + 2) * 3
.
It's the same in Haskell. You need to pass two values to intCMP
, which you can do like this:
Prelude> intCMP (head xs) (head (tail xs))
LT
Basically, you only need to move the brackets around a bit.
Upvotes: 4
Reputation: 15959
You have to set the parentheses differently
intCMP (head xs) (head $ tail xs)
Because in haskell function application is just white space.
Your expression is parsed as intCMP head xs head (tail xs)
which is not what you intended.
Upvotes: 1