Variadic Functions in Haskell

Here’s a function that will take an arbitrary number of Ints as arguments.

import Printf

sum :: [Int] -> IO ()
sum nums = do
    print nums
    let total = sum' nums
    print total

sum' :: [Int] -> Int
sum' [] = 0
sum' (x:xs) = x + sum' xs

main :: IO ()
main = do
    sum [1, 2]
    sum [1, 2, 3]
    let nums = [1, 2, 3, 4]
    sum nums

To run the program, save the code to a file named VariadicFunctions.hs and use runghc to execute it.

$ runghc VariadicFunctions.hs
[1,2]
3
[1,2,3]
6
[1,2,3,4]
10

If you prefer to compile the program, use ghc.

$ ghc --make VariadicFunctions
$ ./VariadicFunctions
[1,2]
3
[1,2,3]
6
[1,2,3,4]
10

Now that we can run and build basic Haskell programs, let’s learn more about the language.