I want write a polymorphic function (e.g. mod) with a fixed type in the second argument, the type of the return value is determined by the first argument. Here is my implementation:
f :: Integral a => a -> Int -> a
f n m = mod n m
and it got error:
Couldn't match expected type ‘a’ with actual type ‘Int’
‘a’ is a rigid type variable bound by
the type signature for:
f :: forall a. Integral a => a -> Int -> a
If I don't want to write two functions with specific type of the first argument (f1 :: Int -> Int -> Int and f2 :: Integer -> Int -> Integer), is there a more elegant implementation?
CodePudding user response:
mod requires both its arguments to be of the same type. So, use fromIntegral to convert m from an Int to type a:
f :: Integral a => a -> Int -> a
f n m = mod n (fromIntegral m)
