Home > Blockchain >  Couldn't match type 'b' with Int
Couldn't match type 'b' with Int

Time:11-09

Task: Transform a list of numbers using map so every even number gets divided by 2 and every odd number gets multiplied by 2

prel2 :: (Fractional b) => [Int] -> [b]
prel2 x = map prel x
     where prel y
        |even y = y/2
        |otherwise = y*2

I know this is some basic stuff, but I can't figure out why the error is raised

CodePudding user response:

Your type signature promises that you can provide a list of values of any type that has a Fractional instance. But, since y is always an Int (since x :: [Int]), then y*2 will always be an Int, and y/2 wouldn't type-check at all.

What you probably want is to use div instead of / to replace the Fractional constraint with an Integral constraint, then generalize your type to Integral b => [b] -> [b].

  • Related