Home > Back-end >  What does it means Instance of Num (Maybe Int) required for definition of mayor
What does it means Instance of Num (Maybe Int) required for definition of mayor

Time:10-20

mayor ::[Integer] -> Integer -> Maybe Int
mayor [] _ = 0
mayor (x:xs) y = if x > y then findIndex (==x) (x:xs) else mayor xs y

Why do I get the error "Instance of Num (Maybe Int) required for definition of mayor"

CodePudding user response:

On the second line you use the literal 0, you probably intend this to have type Int. If you add that as a type signature, you will get a more informative error:

mayor ::[Integer] -> Integer -> Maybe Int
mayor [] _ = 0 :: Int
mayor (x:xs) y = if x > y then findIndex (==x) (x:xs) else mayor xs y
B.hs:3:14: error:
    • Couldn't match expected type ‘Maybe Int’ with actual type ‘Int’
    • In the expression: 0 :: Int
      In an equation for ‘mayor’: mayor [] _ = 0 :: Int
  |
3 | mayor [] _ = 0 :: Int
  |              ^^^^^^^^

Now you can see that the type signature of your function specifies that it will return a value of type Maybe Int, but in your code you return a value of type Int.

You can fix this by wrapping 0 in the Just wrapper:

mayor ::[Integer] -> Integer -> Maybe Int
mayor [] _ = Just 0
mayor (x:xs) y = if x > y then findIndex (==x) (x:xs) else mayor xs y

This will fix the errors, but I don't think this does what you expect (hint: findIndex (== x) (x:xs) will always return Just 0).

  • Related