Home > Back-end >  Can you handle both Int and Float while defining a function in Haskell?
Can you handle both Int and Float while defining a function in Haskell?

Time:10-03

I'm working on a Haskell problem to try and learn the language. I'm trying to recursively add all of the elements in a list, so:

[5,5] -> 10 and [5.0, 5.0] -> 10.0

I know how to recursively solve this, but my question is, how do you handle both Ints and Floats when defining a function? Right now I have:

add :: [Int] -> Int

which doesn't work for float. Thank you in advance for the help.

CodePudding user response:

As indicated in the comments, you're looking for a typeclass. In this particular case, since you want to add numbers together, you want the Num typeclass, which (among other things) provides the addition function

( ) :: Num a => a -> a -> a

So your signature should look like

add :: Num a => [a] -> a

and the function can be written recursively

add [] = 0
add (x:xs) = x   add xs

Note that integer literals, such as 0 in this example, are internally treated as Num a => a. Effectively, the Haskell compiler will compile the number 0 to fromInteger (0 :: Integer), where fromInteger is another function in the Num typeclass. Hence, integer literals are polymorphic.

Finally, while there's nothing wrong with this implementation, the function you're looking at actually comes built-in to Haskell. It's called sum.

sum :: (Foldable t, Num a) => t a => a

Note that Foldable is a typeclass for, fittingly, things that can be folded over. The list type [] is an example of a Foldable.

  • Related