Comparisment

   - compare programming languages by example

43

Varying function arguments

Pass a varying number of arguments into a function.

Created by sam

Add a new answer

Either add an answer for a new language or add an alternative solution.
A description is only necessary when the code is not suitably 'obvious' or to justify an alternative approach.

Haskell

{-# LANGUAGE FlexibleInstances #-}
class PolyOr b where
  polyOr :: Bool -> b

instance PolyOr Bool where
  polyOr b = b

instance PolyOr r => PolyOr (Bool -> r) where
    polyOr b0 = \b1 -> polyOr (b0 || b1)

false :: Bool
false = polyOr False False

true :: Bool
true = polyOr False False False True

By using typeclasses and following this general pattern, variadic functions can be created. This requires the 'FlexibleInstances' pragma and often a return type annotation on the usage of the variadic function.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

def printAll(*args):
  for arg in args:
    print(arg)

def printOneTwoThree(): printAll(1,2,3)
def printNothing(): printAll()

A varying number of arguments can be passed to a function by denoting a collection of the arguments with '*'.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

def greetAndPrint(greeting,*args):
  print(greeting)
  for arg in args:
    print arg

def greetOneTwoThree(): greetAndPrint("Sup?",1,2,3)
def greet(): greetAndPrint("Sup?")

Regular arguments can be declared before variable arguments which must be passed last.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

def greetAndPrint(greeting,*varArgs,**keywordArgs):
  print(greeting)
  for arg in varArgs:
    print arg
  if keywordArgs:
    print keywordArgs

def greetOneTwoThreeMore(): greetAndPrint("Sup?",1,2,3,four=4,more=5)
def greetOneTwoThree(): greetAndPrint("Sup?",1,2,3)
def greet(): greetAndPrint("Sup?")

Regular arguments, varying arguments and keyword arguments may all be mixed and matched provided the varying arguments appear after required arguments.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.