Variadic Functions in Idris

Here’s the example translated to Idris as requested.

Variadic functions can be called with any number of trailing arguments. Here’s an example that takes an arbitrary number of Ints as arguments.

module Main

import Data.List

sum : List Int -> Int
sum nums = total 
  where total = foldl (+) 0 nums

main : IO ()
main = do
  let nums1 = [1, 2]
  putStrLn $ show nums1 ++ " " ++ show (sum nums1)
  
  let nums2 = [1, 2, 3]
  putStrLn $ show nums2 ++ " " ++ show (sum nums2)
  
  let nums3 = [1, 2, 3, 4]
  putStrLn $ show nums3 ++ " " ++ show (sum nums3)

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

Within the function, the type of nums is equivalent to List Int. We can iterate over it with functions like foldl.

Variadic functions can be called in the usual way with individual arguments. If you already have multiple arguments in a list, you can directly pass it to the function.

To run the program, put the code in VariadicFunctions.idr and use idris to execute it:

$ idris -o VariadicFunctions VariadicFunctions.idr  
$ ./VariadicFunctions
[1,2] 3
[1,2,3] 6
[1,2,3,4] 10

Another key aspect of functions in Idris is their ability to form closures, which we’ll look at next.