haskell

Get sum of int or integer in Haskell


This function should work for both lists of Int and lists of Integer:

myFunc :: [Integer] -> [Char]
myFunc x =  if (sum x `mod` 2 ==1) then "odd" else "even"

But it only works on lists of Integers.


Solution

  • Typeclasses provide a way to be generic about types (they're literally a way to internally tag groups of types as having common named methods and/or named values). You can use a typeclass constraint instead of the explicit type Integer, like this:

    myFunc :: Integral a => [a] -> String
    myFunc x = if (even (sum x)) then "even" else "odd"
    

    What this will do is specify that it's a function from [a] to String where a is a type variable, and is constrained to be any type so long as it's a member of the Integral typeclass. Another way to say this is any type so long as it has an instance for the Integral typeclass. That means it has the typeclass's methods specified for that particular type.

    The Integral typeclass is for types whose values are whole numbers (ie the integrals).

    Happily both Int and Integer have an instance provided for Integral, so we can use that.