Get int or integer sum in Haskell

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

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

But it only works on integer lists.

+4
source share
2 answers

Typeclasses provide a way to be generic types (they are groups of types). You can use a typeclass type restriction instead of an explicit type Integer, for example:

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

, , [a] String, a - , , Integral. , Integral. , typeclass, .

Integral , (.. ).

, Int Integer Integral, .

+6

Int - . , Integral typeclass, "mod" .

, , , [] → [Char] [Int] → [Char], , ; [a] → [Char]. , - :

1) , x .

sum :: Num a => [a] -> a; 

Num - , , Num (+), ; .

2) mod , x , Integral. ,

mod (sum x) :: Integral a => a -> a

, Num, x ,

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

, (.. myFunc:: Integral a = > [a] → [Char]), , . , , , - . , .

+3

Source: https://habr.com/ru/post/1682583/


All Articles