I am a beginner in Haskell, I looked at a lot of resources online but I still cannot figure out why the following snippet will not run:
isDivisor :: Int -> Int -> Bool
isDivisor a b =
b % a == 0
The code is supposed to take two integers a and b and it needs to figure out if a is a divisor of b. Now Haskell gives me the following:
• In the type ‘Int -> Int -> Bool isDivisor a b’
In a pattern type signature: Int -> Int -> Bool isDivisor a b
In the pattern: isDivisor :: Int -> Int -> Bool isDivisor a b
I have no idea why this happens. If someone can explain it to me it would be great!
Edit:
Some people suggested I do the following:
isDivisor :: Int -> Int -> Bool
isDivisor a b =
b % a == 0
Now it gives me:
Variable not in scope: (%) :: Int -> Bool -> Bool
After reading some suggestions I arrived at:
isDivisor :: Int -> Int -> Bool
isDivisor a b = b mod a == 0
It gives me:
• Couldn't match expected type ‘(a0 -> a0 -> a0) -> Int -> a1’
with actual type ‘Int’
• The function ‘b’ is applied to two value arguments,
but its type ‘Int’ has none
In the first argument of ‘(==)’, namely ‘b mod a’
In the expression: b mod a == 0
>Solution :
Your code is equivalent to
isDivisor :: Int -> Int -> Bool isDivisor a b =
b % a == 0
You can’t indent the first line of the definition; it treats that line as a continuation of the annotation. a and b in the annotation are type variables, and the result definition uses undefined variables a and b.
Instead, write
isDivisor :: Int -> Int -> Bool
isDivisor a b =
b `mod` a == 0
((%) is not defined as the modulo operator in Haskell; you are looking for the mod function. % is defined by Data.Ratio for use in constructing values of type Ratio a.)