Comparisment

   - compare programming languages by example

42

Named function arguments

Pass arguments by name into functions.

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 RecordWildCards #-}
data Person = Person
  {personName :: String
  ,personAge  :: Int
  }

greet :: Person -> String
greet (Person{..}) = "Greetings " ++ personName ++ ", age " ++ show personAge

greetBob :: String
greetBob = let personAge  = 42
               personName = "Bob"  
            in greet (Person{..})

The language pragma 'RecordWildCards' can be used to automatically bind fields within a record type to like-named variables in the current scope. This also works in 'reverse', binding correspondingly named variables in scope in the creation of new data. The effect is that this feature can be used to simulate named function arguments.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

def greet(name,age):
  print('Hello ' + str(name) + ', age ' + str(age))

def greetBob(): greet(age=42,name='bob')

As well as positionally, functions can be called with their named arguments in any order.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.