Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Named_parameters
note: Basic language learning

View file

@ -0,0 +1,14 @@
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
'''Note:'''
: Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called.
: For example, if a function were to be defined as <code>define func1( paramname1, paramname2)</code>; then it could be called normally as <code>func1(argument1, argument2)</code> and in the called function paramname1 would be associated with argument1 and paramname2 with argument2.
: <code>func1</code> '''must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order''', for example: <code>func1(paramname2=argument2, paramname1=argument1)</code> which ''explicitly'' makes the same parameter/argument bindings as before.
: Named parameters are often a feature of languages used in safety critical areas such as [[wp:Verilog|Verilog]] and [[wp:VHDL|VHDL]].
'''See also:'''
* [[Varargs]]
* [[Optional parameters]]
* [[wp:Named parameter|Wikipedia: Named parameter]]
<br><br>

View file

@ -0,0 +1,4 @@
F sqlen(x = 0, y = 0, z = 0)
R x*x + y*y + z*z
print(sqlen(z' 3)) // equivalent to print(sqlen(0, 0, 3))

View file

@ -0,0 +1,36 @@
BEGIN
MODE OPTNAME = STRUCT(STRING name),
OPTSPECIES = STRUCT(STRING species),
OPTBREED = STRUCT(STRING breed),
OWNER=STRUCT(STRING first name, middle name, last name);
# Version 2 of Algol 68G would not allow empty options to be specified as () so #
# VOID would need to be included in the MODEs for options and Empty option lists #
# would need to be written as (EMPTY) #
MODE OPTIONS = FLEX[1:0]UNION(OPTNAME,OPTSPECIES,OPTBREED,OWNER); # add ,VOID for Algol 68G version 2 #
# due to the Yoneda ambiguity simple arguments must have an unique operator defined #
# E.g. a string cannot be coerced to a structure with a single string field #
OP NAME = (STRING name)OPTNAME: (OPTNAME opt; name OF opt := name; opt),
SPECIES = (STRING species)OPTSPECIES: (OPTSPECIES opt; species OF opt := species; opt),
BREED = (STRING breed)OPTBREED: (OPTBREED opt; breed OF opt := breed; opt);
PROC print pet = (OPTIONS option)VOID: (
STRING name:="Rex", species:="Dinosaur", breed:="Tyrannosaurus"; # Defaults #
OWNER owner := ("George","W.","Bush");
FOR i TO UPB option DO
CASE option[i] IN
(OPTNAME option): name := name OF option,
(OPTSPECIES option): species := species OF option,
(OPTBREED option): breed := breed OF option,
(OWNER option): owner := option
ESAC
OD;
print(("Details: "
,IF CHAR c = breed[LWB breed]; char in string( c, NIL, "AaEeIiOoUu" ) THEN "an " ELSE "a " FI
,breed, " ", species, " named ",name," owned by ",owner, newline))
);
print pet((NAME "Mike", SPECIES "Dog", BREED "Irish Setter", OWNER("Harry", "S.", "Truman")));
print pet(()) # use print pet((EMPTY)) for Algol 68G version 2 #
END

View file

@ -0,0 +1 @@
procedure Foo (Arg_1 : Integer; Arg_2 : Float := 0.0);

View file

@ -0,0 +1,4 @@
Foo (1, 0.0);
Foo (1);
Foo (Arg_2 => 0.0, Arg_1 => 1);
Foo (Arg_1 => 1);

View file

@ -0,0 +1,11 @@
on getName(x)
set {firstName, lastName} to {"?", "?"}
try
set firstName to x's firstName
end try
try
set lastName to x's lastName
end try
return firstName & ", " & lastName
end getName

View file

@ -0,0 +1,4 @@
getName({firstName:"John", lastName:"Doe"})
--> Returns: "John, Doe"
getName({lastName:"Doe"})
--> Returns: "?, Doe"

View file

@ -0,0 +1,8 @@
on getName(x) -- x assumed to be a record for this demo.
set x to x & {firstName:"?", lastName:"?"}
return x's firstName & ", " & x's lastName
end getName
getName({lastName:"Doe"})
--> "?, Doe"

View file

@ -0,0 +1,6 @@
on getName from firstName beside lastName
return firstName & ", " & lastName
end getName
getName beside "Doe" from "John"
--> "John, Doe"

View file

@ -0,0 +1,6 @@
on getName given firstName:firstName, lastName:lastName
return firstName & ", " & lastName
end getName
getName given lastName:"Doe", firstName:"John"
--> "John, Doe"

View file

@ -0,0 +1,12 @@
on getName given firstName:firstName, lastName:lastName, comma:comma
if (comma) then
return firstName & ", " & lastName
else
return firstName & space & lastName
end if
end getName
getName given lastName:"Doe", firstName:"John" comma:true -- compiles as: getName with comma given lastName:"Doe", firstName:"John"
--> "John, Doe"
getName without comma given lastName:"Doe", firstName:"John"
--> "John Doe"

View file

@ -0,0 +1,12 @@
use AppleScript version "2.4" -- Mac OS X 10.10 (Yosemite) or later.
on getName under category : "Misc: " given firstName:firstName : "?", lastName:lastName : "?", comma:comma : true
if (comma) then
return category & firstName & ", " & lastName
else
return category & firstName & space & lastName
end if
end getName
getName given lastName:"Doe"
--> "Misc: ?, Doe"

View file

@ -0,0 +1,6 @@
100 IF LAST$ = "" THEN PRINT "?";
110 IF LAST$ < > "" THEN PRINT LAST$;
120 IF FIRST$ < > "" THEN PRINT ", "FIRST$;
200 FIRST$ = ""
210 LAST$ = ""
220 RETURN

View file

@ -0,0 +1,12 @@
func: function [x][
print ["argument x:" x]
print ["attribute foo:" attr 'foo]
print ["attribute bar:" attr 'bar]
print ""
]
func 1
func .foo:"foo" 2
func .bar:"bar" 3
func .foo:123 .bar:124 4
func .bar:124 .foo:123 5

View file

@ -0,0 +1,12 @@
MyFunc( "Val=0, w=1024, Text=The Quick Brown Fox, newVar=I'm New" )
MyFunc( _overrides="" ) {
Static x=5, y=5, w=100, h=100, Count
Name:="AutoHotkey", Type:="Scripting", Text:="qwerty", Val:=True
Loop, Parse, _overrides,`,=, %A_Space% ; Override routine for Local/Static variables
A_Index & 1 ? (_:=A_LoopField) : (%_%:=A_LoopField)
Listvars
WinWaitClose, %A_ScriptFullPath%
}

View file

@ -0,0 +1,20 @@
( ( testproc
= i x y z
. out$"Calling testproc"
& (=~):(=?i:?x:?y:?z) { initialise variables to 'failure' }
& !arg
: (? (i,?i) ?|?) { if "i" found, assign value to i. Otherwise just match with no side effect. }
: (? (x,?x) ?|?) { if "x" found, assign value to x. Otherwise just match with no side effect. }
: (? (y,?y) ?|?) { likewise }
: (? (z,?z) ?|?) { likewise }
& (~!i|put$(" i:=" !i)) { if variable doesn't fail, show its value }
& (~!x|put$(" x:=" !x))
& (~!y|put$(" y:=" !y))
& (~!z|put$(" z:=" !z))
& put$\n { add new line }
)
& testproc$((x,1) (y,2) (z,3))
& testproc$((x,3) (y,1) (z,2))
& testproc$((z,4) (x,2) (y,3)) { order is not important }
& testproc$((i,1) (y,2) (z,3))
);

View file

@ -0,0 +1,27 @@
class foo_params{
friend void foo(foo_params p);
public:
foo_params(int r):
required_param_(r),
optional_x_(0),
optional_y_(1),
optional_z_(3.1415)
{}
foo_params& x(int i){
optional_x_=i;
return *this;
}
foo_params& y(int i){
optional_y_=i;
return *this;
}
foo_params& z(float f){
optional_z_=f;
return *this;
}
private:
int required_param_;
int optional_x_;
int optional_y_;
float optional_z_;
};

View file

@ -0,0 +1 @@
void foo(foo_params p){ . . .}

View file

@ -0,0 +1 @@
foo(foo_params(42).x(7).z(23.54));

View file

@ -0,0 +1,26 @@
#include <boost/parameter/name.hpp>
#include <boost/parameter/preprocessor.hpp>
#include <string>
BOOST_PARAMETER_NAME(foo)
BOOST_PARAMETER_NAME(bar)
BOOST_PARAMETER_NAME(baz)
BOOST_PARAMETER_NAME(bonk)
BOOST_PARAMETER_FUNCTION(
(int), // the return type of the function, the parentheses are required.
function_with_named_parameters, // the name of the function.
tag, // part of the deep magic. If you use BOOST_PARAMETER_NAME you need to put "tag" here.
(required // names and types of all required parameters, parentheses are required.
(foo, (int))
(bar, (float))
)
(optional // names, types, and default values of all optional parameters.
(baz, (bool) , false)
(bonk, (std::string), "default value")
)
)
{
if (baz && (bar > 1.0)) return foo;
return bonk.size();
}

View file

@ -0,0 +1,5 @@
function_with_named_parameters(1, 10.0);
function_with_named_parameters(7, _bar = 3.14);
function_with_named_parameters( _bar = 0.0, _foo = 42);
function_with_named_parameters( _bar = 2.5, _bonk= "Hello", _foo = 9);
function_with_named_parameters(9, 2.5, true, "Hello");

View file

@ -0,0 +1,20 @@
using System;
namespace NamedParams
{
class Program
{
static void AddWidget(string parent, float x = 0, float y = 0, string text = "Default")
{
Console.WriteLine("parent = {0}, x = {1}, y = {2}, text = {3}", parent, x, y, text);
}
static void Main(string[] args)
{
AddWidget("root", 320, 240, "First");
AddWidget("root", text: "Origin");
AddWidget("root", 500);
AddWidget("root", text: "Footer", y: 400);
}
}
}

View file

@ -0,0 +1,48 @@
#include <stdio.h>
// 1. Named parameters
typedef struct { int x, y, z; } FTest_args;
void FTest (FTest_args args) {
printf("x: %d, y: %d, z: %d\n", args.x, args.y, args.z);
}
#define FT(...) FTest((FTest_args){ __VA_ARGS__ })
// 2. Default parameters
#define DFT(...) FTest((FTest_args){ .x = 142, .y = 143, .z = 144, __VA_ARGS__ })
// 3. Convenience wrapper to avoid accessing args as "args.name"
void FTest2 (int x, int y, int z) {
printf("x: %d, y: %d, z: %d\n", x, y, z);
}
static inline void FTest2_default_wrapper (FTest_args args) {
return FTest2(args.x, args.y, args.z);
}
#define DF2(...) FTest2_default_wrapper((FTest_args){ .x = 142, .y = 143, .z = 144, __VA_ARGS__ })
int main(int argc, char **argv)
{
// Named parameters
FTest((FTest_args){ .y = 10 });
FTest((FTest_args){ .y = 10, .z = 42 });
FT( .z = 47, .y = 10, .x = 42 );
// Default parameters
DFT();
DFT( .z = 99 );
// Default parameters with wrapper
DF2();
DF2( .z = 99 );
return 0;
}

View file

@ -0,0 +1,4 @@
(defn foo [& opts]
(let [opts (merge {:bar 1 :baz 2} (apply hash-map opts))
{:keys [bar baz]} opts]
[bar baz]))

View file

@ -0,0 +1,2 @@
(defn foo [& {:keys [bar baz] :or {bar 1, baz 2}}]
[bar baz])

View file

@ -0,0 +1,3 @@
(use 'clojure.contrib.def)
(defnk foo [:bar 1 :baz 2]
[bar baz])

View file

@ -0,0 +1,6 @@
(defun print-name (&key first (last "?"))
(princ last)
(when first
(princ ", ")
(princ first))
(values))

View file

@ -0,0 +1,8 @@
CL-USER> (print-name)
?
CL-USER> (print-name :first "John")
?, John
CL-USER> (print-name :first "John" :last "Doe")
Doe, John
CL-USER> (print-name :last "Doe")
Doe

View file

@ -0,0 +1,55 @@
program Named_parameters;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TParams = record
fx, fy, fz: Integer;
function x(value: Integer): TParams;
function y(value: Integer): TParams;
function z(value: Integer): TParams;
class function _: TParams; static;
end;
function Sum(Param: TParams): Integer;
begin
Result := Param.fx + Param.fy + Param.fz;
end;
{ TParams }
function TParams.x(value: Integer): TParams;
begin
Result := Self;
Result.fx := value;
end;
function TParams.y(value: Integer): TParams;
begin
Result := Self;
Result.fy := value;
end;
function TParams.z(value: Integer): TParams;
begin
Result := Self;
Result.fz := value;
end;
class function TParams._: TParams;
begin
Result.fx := 0; // default x
Result.fy := 0; // default y
Result.fz := 0; // default z
end;
begin
writeln(sum(TParams._.x(2).y(3).z(4))); // 9
writeln(sum(TParams._.z(4).x(3).y(5))); // 12
{$IFNDEF UNIX} readln; {$ENDIF}
end.

View file

@ -0,0 +1,6 @@
func fun(x, y = 0, z = 12.2, dsc = "Useless text") {
print("x=\(x), y=\(y), z=\(z), dsc=\(dsc)")
}
fun(12, z: 24.4, dsc: "Foo", y: 3)
fun(y: 42, x: 12)

View file

@ -0,0 +1,11 @@
def printName([=> first := null, => last := null]) {
if (last == null) {
print("?")
} else {
print(last)
}
if (first != null) {
print(", ")
print(first)
}
}

View file

@ -0,0 +1,8 @@
? printName(["first" => "John"])
?, John
? printName(["last" => "Doe"])
Doe
? printName(["first" => "John", "last" => "Doe"])
Doe, John

View file

@ -0,0 +1,18 @@
module NamedParams {
const Point(Int x, Int y) {
Point with(Int? x=Null, Int? y=Null) {
return new Point(x ?: this.x, y ?: this.y);
}
}
@Inject Console console;
void run() {
Point origin = new Point(0, 0);
console.print($"origin={origin}");
Point moveRight = origin.with(x=5);
console.print($"moveRight(x=5)={moveRight}");
Point moveUp = moveRight.with(y=3);
console.print($"moveUp(y=3)={moveUp}");
}
}

View file

@ -0,0 +1,3 @@
def fun(bar: bar, baz: baz), do: IO.puts "#{bar}, #{baz}."
fun(bar: "bar", baz: "baz")

View file

@ -0,0 +1,5 @@
Fun = fun( Proplists ) ->
Argument1 = proplists:get_value( argument1, Proplists, 1 ),
Kalle = proplists:get_value( kalle, Proplists, "hobbe" ),
io:fwrite( "~p ~s~n", [Argument1, Kalle] )
end.

View file

@ -0,0 +1,9 @@
type SpeedingTicket() =
member this.GetMPHOver(speed: int, limit: int) = speed - limit
let CalculateFine (ticket : SpeedingTicket) =
let delta = ticket.GetMPHOver(limit = 55, speed = 70)
if delta < 20 then 50.0 else 100.0
let ticket1 : SpeedingTicket = SpeedingTicket()
printfn "%f" (CalculateFine ticket1)

View file

@ -0,0 +1 @@
:: my-named-params ( a b -- c ) a b * ;

View file

@ -0,0 +1,21 @@
256 buffer: first-name
256 buffer: last-name
: is ( a "name" -- ) parse-name rot place ;
: greet ( -- )
cr ." Hello, " first-name count type space last-name count type ." !" ;
first-name is Bob last-name is Hall greet
require mini-oof2.fs
require string.fs
object class
field: given-name
field: surname
end-class Person
: hiya ( -- )
cr ." Hiya, " given-name $. space surname $. ." !" ;
Person new >o s" Bob" given-name $! s" Hall" surname $! hiya o>

View file

@ -0,0 +1,5 @@
subroutine a_sub(arg1, arg2, arg3)
integer, intent(in) :: arg1, arg2
integer, intent(out), optional :: arg3
! ...
end subroutine a_sub

View file

@ -0,0 +1,4 @@
! usage
integer :: r
call a_sub(1,2, r)
call a_sub(arg2=2, arg1=1)

View file

@ -0,0 +1,5 @@
subroutine b_sub(arg1, arg2)
integer, intent(in), optional :: arg1
integer, intent(in) :: arg2
!...
end subroutine b_sub

View file

@ -0,0 +1,4 @@
call b_sub(1) ! error: missing non optional arg2
call b_sub(arg2=1) ! ok
call b_sub(1, 2) ! ok: arg1 is 1, arg2 is 2
call b_sub(arg2=2, arg1=1) ! the same as the previous line

View file

@ -0,0 +1,10 @@
Dim Shared foo As Long, bar As Integer, baz As Byte, qux As String
'la función
Sub LoqueSea(foo As Long, bar As Integer, baz As Byte, qux As String)
'...
End Sub
'llamando a la función
Sub Algo()
LoqueSea(bar = 1, baz = 2, foo = -1, qux = "Probando")
End Sub

View file

@ -0,0 +1,20 @@
package main
import (
"fmt"
)
type params struct {x, y, z int}
func myFunc(p params) int {
return p.x + p.y + p.z
}
func main() {
r := myFunc(params{x: 1, y: 2, z: 3}) // all fields, same order
fmt.Println("r =", r)
s := myFunc(params{z: 3, y: 2, x: 1}) // all fields, different order
fmt.Println("s =", s)
t := myFunc(params{y: 2}) // only one field, others set to zero
fmt.Println("t =", t)
}

View file

@ -0,0 +1,8 @@
data X = X
data Y = Y
data Point = Point Int Int deriving Show
createPointAt :: X -> Int -> Y -> Int -> Point
createPointAt X x Y y = Point x y
main = print $ createPointAt X 5 Y 3

View file

@ -0,0 +1,6 @@
data Point = Point {x, y :: Int} deriving Show
defaultPoint = Point {x = 0, y = 0}
createPointAt :: Point -> Point
createPointAt = id
main = print $ createPointAt (defaultPoint { y = 3, x = 5 })

View file

@ -0,0 +1,20 @@
procedure main()
testproc("x:=",1,"y:=",2,"z:=",3)
testproc("x:=",3,"y:=",1,"z:=",2)
testproc("z:=",4,"x:=",2,"y:=",3)
testproc("i:=",1,"y:=",2,"z:=",3)
end
procedure testproc(A[]) #: demo to test named parameters
write("Calling testproc")
while a := get(A) do # implement named parameters here
(( a ? (v := =!["x","y","z"], =":=") | # valid parameter name?
stop("No parameter ",a)) & # . . no
((variable(a[1:-2]) := get(A)) | # assign
runerr(205,a))) # . . problem
write(" x:=",x)
write(" y:=",y)
write(" z:=",z)
end

View file

@ -0,0 +1,26 @@
NB. Strand notation
myFunc['c:\file.txt' 906 'blue' fs]
NB. Commas, like other langs
myFunc['c:\file.txt', 906, 'blue' fs]
NB. Unspecified args are defaulted ("optional")
myFunc['c:\file.txt' fs]
NB. Can use named arguments, like eg VB
myFunc[color='blue' fs]
NB. Often values needn't be quoted
myFunc[color= blue fs]
NB. Combination of comma syntax and name=value
myFunc[max=906, color=blue fs]
NB. Spelling of names is flexible
myFunc[MAX=906, COLOR=blue fs]
NB. Order of names is flexible
myFunc[COLOR=blue, MAX=906 fs]
NB. Even the delimiters are flexible...
myFunc<MAX=906, COLOR=blue fs>

View file

@ -0,0 +1 @@
processNutritionFacts(new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build());

View file

@ -0,0 +1,12 @@
function example(options) {
// assign some defaults where the user's has not provided a value
opts = {}
opts.foo = options.foo || 0;
opts.bar = options.bar || 1;
opts.grill = options.grill || 'pork chops'
alert("foo is " + opts.foo + ", bar is " + opts.bar + ", and grill is " + opts.grill);
}
example({grill: "lamb kebab", bar: 3.14});
// => "foo is 0, bar is 3.14, and grill is lamb kebab"

View file

@ -0,0 +1,12 @@
let
example = // The member name in the object can either be the same as the parameter (as in bar, grill),
// or a different parameter name as in the case of member foo being assigned to parameter a here.
({foo: a=0, bar=1, grill='pork chops'}={}) => (
console.log('foo is ',a,', bar is ',bar,', and grill is '+grill));
example();
// foo is 0 , bar is 1 , and grill is pork chops
example({grill: "lamb kebab", bar: 3.14});
// foo is 0 , bar is 3.14 , and grill is lamb kebab
example({foo:null});
// foo is , bar is 1 , and grill is pork chops

View file

@ -0,0 +1,7 @@
def formatName(obj):
({ "name": "?"} + obj) as $obj # the default default value is null
| ($obj|.name) as $name
| ($obj|.first) as $first
| if ($first == null) then $name
else $name + ", " + $first
end;

View file

@ -0,0 +1,9 @@
formatName({"first": "George", "name": "Eliot"})
formatName({"name": "Eliot", "first": "George"})
formatName({"name": "Eliot"})
formatName({"first": "George"})
formatName({})

View file

@ -0,0 +1,14 @@
function surround(string ; border = :default, padding = 0)
ve, ho, ul, ur, dl, dr =
border == :round ? ("\u2502","\u2500","\u256d","\u256e","\u2570","\u256f") :
border == :bold ? ("\u2503","\u2501","\u250F","\u2513","\u2517","\u251b") :
border == :double ? ("\u2551","\u2550","\u2554","\u2557","\u255a","\u255d") :
border == :dotted ? ("\u254e","\u254c","\u250c","\u2510","\u2514","\u2518") :
border == :cross ? ("\u2502","\u2500","\u253c","\u253c","\u253c","\u253c") :
("\u2502","\u2500","\u250c","\u2510","\u2514","\u2518")
println(ul, ho^(length(string) + 2padding), ur, "\n",
ve, " "^padding, string," "^padding, ve, "\n",
dl, ho^(length(string) + 2padding), dr)
end

View file

@ -0,0 +1,19 @@
// version 1.0.6
fun someFunction(first: String, second: Int = 2, third: Double) {
println("First = ${first.padEnd(10)}, Second = $second, Third = $third")
}
fun main(args: Array<String>) {
// using positional parameters
someFunction("positional", 1, 2.0)
// using named parameters
someFunction(first = "named", second = 1, third = 2.0)
// omitting 2nd parameter which is optional because it has a default value
someFunction(first = "omitted", third = 2.0)
// using first and third parameters in reverse
someFunction(third = 2.0, first = "reversed")
}

View file

@ -0,0 +1,16 @@
define mymethod(
-first::integer, // with no default value the param is required
-second::integer,
-delimiter::string = ':' // when given a default value the param becomes optional
) => #first + #delimiter + #second
mymethod(
-first = 54,
-second = 45
)
'<br />'
mymethod(
-second = 45, // named params can be given in any order
-first = 54,
-delimiter = '#'
)

View file

@ -0,0 +1,22 @@
-- accepts either 3 integers or a single property list
on foo (arg1, arg2, arg3)
if ilk(arg1)=#propList then
args = arg1
arg1 = args[#arg1]
arg2 = args[#arg2]
arg3 = args[#arg3]
end if
put "arg1="&arg1
put "arg2="&arg2
put "arg3="&arg3
end
foo(1,2) -- 3rd argument omitted
-- "arg1=1"
-- "arg2=2"
-- "arg3="
foo([#arg3:3]) -- only 3rd argument specified
-- "arg1="
-- "arg2="
-- "arg3=3"

View file

@ -0,0 +1,8 @@
function CreatePet(options)
local name=options.name
local species=options.species
local breed=options.breed
print('Created a '..breed..' '..species..' named '..name)
end
CreatePet{name='Rex',species='Dog',breed='Irish Setter'}
--position does not matter here.

View file

@ -0,0 +1,14 @@
module namedparam (x as decimal=10, y as integer=50) {
Print type$(x), x
Print type$(y), y
}
namedparam 10, 20
namedparam ?, ?
Push 1, 2 : namedparam
Stack New {
\\ it is empty
namedparam
namedparam %y=500
namedparam %x=20
}
namedparam %x=1, %y=1

View file

@ -0,0 +1,15 @@
function foo(varargin)
for k= 1:2:length(varargin);
switch (varargin{k})
case {'param1'}
param1 = varargin{k+1};
case {'param2'}
param2 = varargin{k+1};
end;
end;
printf('param1: %s\n',param1);
printf('param2: %s\n',param2);
end;
foo('param1','a1','param2','b2');
foo('param2','b2','param1','a1');

View file

@ -0,0 +1,10 @@
f := proc(a, {b:= 1, c:= 1})
print (a*(c+b));
end proc:
#a is a mandatory positional parameter, b and c are optional named parameters
f(1);#you must have a value for a for the procedure to work
2
f(1, c = 1, b = 2);
3
f(2, b = 5, c = 3);#b and c can be put in any order
16

View file

@ -0,0 +1,4 @@
Options[fn]={Add->False,Offset-> 0};
fn[x_,y_,OptionsPattern[]]:=If[OptionValue[Add]==True,x+y+OptionValue[Offset],{x,y,OptionValue[Offset]}]
fn[3,4,{Add->True,Offset->2}]
fn[3,4,{Offset->2,Add->True}]

View file

@ -0,0 +1 @@
PROCEDURE Foo(Arg1: INTEGER; Arg2: REAL := 0.0);

View file

@ -0,0 +1,4 @@
Foo(1, 0.0);
Foo(1);
Foo(Arg2 := 0.0, Arg1 := 1);
Foo(Arg1 := 1);

View file

@ -0,0 +1,4 @@
Foo(number : int, word = "Default", option = true) : void // note type inference with default values
Foo(word = "Bird", number = 3) // an argument with a default value can be omitted from function call
Foo(3, option = false, word = "Bird") // unnamed arguments must be in same order as function definition and precede named arguments

View file

@ -0,0 +1,4 @@
proc subtract(x, y): auto = x - y
echo subtract(5, 3) # used as positional parameters
echo subtract(y = 3, x = 5) # used as named parameters

View file

@ -0,0 +1,8 @@
# let foo ~arg1 ~arg2 = arg1 + arg2;;
val foo : arg1:int -> arg2:int -> int = <fun>
# let foo ~arg1:x ~arg2:y = x + y;; (* you can also use different variable names internally if you want *)
val foo : arg1:int -> arg2:int -> int = <fun>
# foo ~arg2:17 ~arg1:42;;
- : int = 59

View file

@ -0,0 +1,8 @@
@interface Demo : NSObject {
// Omitted ...
}
- (double) hypotenuseOfX: (double)x andY: (double)y;
- (double) hypotenuseOfX: (double)x andY: (double)y andZ: (double)z;
@end

View file

@ -0,0 +1,10 @@
@implementation Demo
- (double) hypotenuseOfX: (double)x andY: (double)y {
return hypot(x,y);
}
- (double) hypotenuseOfX: (double)x andY: (double)y andZ: (double)z {
return hypot(hypot(x, y), z);
}
@end

View file

@ -0,0 +1,2 @@
Demo *example = [[Demo alloc] init];
double h = [example hypotenuseOfX:1.23 andY:3.79];

View file

@ -0,0 +1,15 @@
declare
class Foo
meth init skip end
meth bar(PP %% positional parameter
named1:N1
named2:N2
namedWithDefault:NWD <= 42)
{System.showInfo "PP: "#PP#", N1: "#N1#", N2: "#N2#", NWD: "#NWD}
end
end
O = {New Foo init}
{O bar(1 named1:2 named2:3 namedWithDefault:4)} %% ok
{O bar(1 named2:2 named1:3)} %% ok
{O bar(1 named1:2)} %% not ok, "missing message feature in object application"

View file

@ -0,0 +1,10 @@
declare
proc {Foo PP Other=unit(named1:N1 named2:N2 ...)}
NWD = {CondSelect Other namedWithDefault 42}
in
{System.showInfo "PP: "#PP#", N1: "#N1#", N2: "#N2#", NWD: "#NWD}
end
{Foo 1 unit(named1:2 named2:3 namedWithDefault:4)}
{Foo 1 unit(named2:2 named1:3)}
{Foo 1 unit(named1:2)} %% not ok...

View file

@ -0,0 +1,8 @@
function named($args) {
$args += ["gbv" => 2,
"motor" => "away",
"teenage" => "fbi"];
echo $args["gbv"] . " men running " . $args['motor'] . " from the " . $args['teenage'];
}
named(["teenage" => "cia", "gbv" => 10]);

View file

@ -0,0 +1,12 @@
sub funkshun {
my %h = @_;
# Print every argument and its value.
print qq(Argument "$_" has value "$h{$_}".\n)
foreach sort keys %h;
# If a 'verbosity' argument was passed in, print its value
# whatever that value may be.
print "Verbosity specified as $h{verbosity}.\n" if exists $h{verbosity};
# Say that safe mode is on if 'safe' is set to a true value.
# Otherwise, say that it's off.
print "Safe mode ", ($h{safe} ? 'on' : 'off'), ".\n";
}

View file

@ -0,0 +1,7 @@
funkshun(
verbosity => 3,
password => 'foobie blech',
extra_lives => 3,
'42' => 'answer',
password => 'joshua'
);

View file

@ -0,0 +1,37 @@
sub event
{
my ($params_ref, $name) = @_;
my %params = %$params_ref;
my @known_params = qw(attendees event food time);
printf "%s called event() with the following named parameters:\n",
$name // 'Anonymous';
say sort map {
sprintf "%s: %s\n",
ucfirst $_,
ref $params{$_} eq ref []
? join ', ', @{ $params{$_} }
: $params{$_};
} grep exists $params{$_}, @known_params;
delete $params{$_} foreach @known_params;
say "But I didn't recognize these ones:";
while (my ($key, $val) = each %params)
{
say "$key: $val";
}
}
event(
{ # Curly braces with no label (e.g. 'sub' before it)
# create a reference to an anonymous hash
attendees => ['Bob', 'Betty', 'George', 'Bertha'],
event => 'birthday',
foo => 'bar',
food => 'cake',
frogblast => 'vent core',
time => 3,
},
"Joe Schmoe"
);

View file

@ -0,0 +1,3 @@
-->
<span style="color: #008080;">global</span> <span style="color: #008080;">function</span> <span style="color: #000000;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">weeks</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">days</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hours</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">minutes</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">seconds</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">milliseconds</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">microseconds</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<!--

View file

@ -0,0 +1,16 @@
(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">days</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hours</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">fourdays</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #000000;">days</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">4</span><span style="color: #0000FF;">),</span>
<span style="color: #000080;font-style:italic;">-- fourdays = timedelta(0,4) -- equivalent, **NB** a plain '=' is a very different thing:</span>
<span style="color: #000000;">slipup</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #000000;">days</span><span style="color: #0000FF;">=</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- === timedelta([weeks:=]iff(equal(days,4)?true:false))
-- with error if no local/in scope identifier days exists.</span>
<span style="color: #000000;">shift</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">timedelta</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hours</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">hours</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- perfectly valid (param hours:=local hours)
-- timedelta(0,hours:=15,3) -- illegal (not clear whether days:=3 or minutes:=3)
-- though of course the weeks:=0 part is fine</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"fourdays = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fourdays</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"wrong = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">slipup</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"shift = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shift</span><span style="color: #0000FF;">)})</span>
<!--

View file

@ -0,0 +1,6 @@
(de foo @
(bind (rest) # Bind symbols in CARs to values in CDRs
(println 'Bar 'is Bar)
(println 'Mumble 'is Mumble) ) )
(foo '(Bar . 123) '(Mumble . "def"))

View file

@ -0,0 +1,7 @@
(de foo @
(bind (next) # Save all symbols in first argument
(mapc set (arg) (rest)) # then bind them to remaining arguments
(println 'Bar 'is Bar)
(println 'Mumble 'is Mumble) ) )
(foo '(Bar Mumble) 123 "def")

View file

@ -0,0 +1,3 @@
function Test {
Write-Host Argument 1 is $args[0]
}

View file

@ -0,0 +1,5 @@
function Test ($SomeArgument, $AnotherArgument, $ThirdArgument) {
Write-Host "Some argument: $SomeArgument"
Write-Host "Another argument: $AnotherArgument"
Write-Host "Third argument: $ThirdArgument"
}

View file

@ -0,0 +1,3 @@
function SwitchTest ([switch] $on) {
Write-Host Switched $(if ($on) { "on" } else { "off" })
}

View file

@ -0,0 +1,3 @@
function Greeting ($Name = "Nobody") {
Write-Host Hello, $Name!
}

View file

@ -0,0 +1,14 @@
:- initialization(main).
main :-
sum(b=2,output=Output,a=1),
writeln(Output).
sum(A1,B1,C1) :-
named_args([A1,B1,C1],[a=A,b=B,output=Output]),
Output is A + B.
named_args([],_).
named_args([A|B],C) :-
member(A,C),
named_args(B,C).

View file

@ -0,0 +1,5 @@
def subtract(x, y):
return x - y
subtract(5, 3) # used as positional parameters; evaluates to 2
subtract(y = 3, x = 5) # used as named parameters; evaluates to 2

View file

@ -0,0 +1,107 @@
>>> from __future__ import print_function
>>>
>>> def show_args(defparam1, defparam2 = 'default value', *posparam, **keyparam):
"Straight-forward function to show its arguments"
print (" Default Parameters:")
print (" defparam1 value is:", defparam1)
print (" defparam2 value is:", defparam2)
print (" Positional Arguments:")
if posparam:
n = 0
for p in posparam:
print (" positional argument:", n, "is:", p)
n += 1
else:
print (" <None>")
print (" Keyword Arguments (by sorted key name):")
if keyparam:
for k,v in sorted(keyparam.items()):
print (" keyword argument:", k, "is:", v)
else:
print (" <None>")
>>> show_args('POSITIONAL', 'ARGUMENTS')
Default Parameters:
defparam1 value is: POSITIONAL
defparam2 value is: ARGUMENTS
Positional Arguments:
<None>
Keyword Arguments (by sorted key name):
<None>
>>> show_args(defparam2='ARGUMENT', defparam1='KEYWORD')
Default Parameters:
defparam1 value is: KEYWORD
defparam2 value is: ARGUMENT
Positional Arguments:
<None>
Keyword Arguments (by sorted key name):
<None>
>>> show_args( *('SEQUENCE', 'ARGUMENTS') )
Default Parameters:
defparam1 value is: SEQUENCE
defparam2 value is: ARGUMENTS
Positional Arguments:
<None>
Keyword Arguments (by sorted key name):
<None>
>>> show_args( **{'defparam2':'ARGUMENTS', 'defparam1':'MAPPING'} )
Default Parameters:
defparam1 value is: MAPPING
defparam2 value is: ARGUMENTS
Positional Arguments:
<None>
Keyword Arguments (by sorted key name):
<None>
>>> show_args('ONLY DEFINE defparam1 ARGUMENT')
Default Parameters:
defparam1 value is: ONLY DEFINE defparam1 ARGUMENT
defparam2 value is: default value
Positional Arguments:
<None>
Keyword Arguments (by sorted key name):
<None>
>>> show_args('POSITIONAL', 'ARGUMENTS',
'EXTRA', 'POSITIONAL', 'ARGUMENTS')
Default Parameters:
defparam1 value is: POSITIONAL
defparam2 value is: ARGUMENTS
Positional Arguments:
positional argument: 0 is: EXTRA
positional argument: 1 is: POSITIONAL
positional argument: 2 is: ARGUMENTS
Keyword Arguments (by sorted key name):
<None>
>>> show_args('POSITIONAL', 'ARGUMENTS',
kwa1='EXTRA', kwa2='KEYWORD', kwa3='ARGUMENTS')
Default Parameters:
defparam1 value is: POSITIONAL
defparam2 value is: ARGUMENTS
Positional Arguments:
<None>
Keyword Arguments (by sorted key name):
keyword argument: kwa1 is: EXTRA
keyword argument: kwa2 is: KEYWORD
keyword argument: kwa3 is: ARGUMENTS
>>> show_args('POSITIONAL',
'ARGUMENTS', 'EXTRA', 'POSITIONAL', 'ARGUMENTS',
kwa1='EXTRA', kwa2='KEYWORD', kwa3='ARGUMENTS')
Default Parameters:
defparam1 value is: POSITIONAL
defparam2 value is: ARGUMENTS
Positional Arguments:
positional argument: 0 is: EXTRA
positional argument: 1 is: POSITIONAL
positional argument: 2 is: ARGUMENTS
Keyword Arguments (by sorted key name):
keyword argument: kwa1 is: EXTRA
keyword argument: kwa2 is: KEYWORD
keyword argument: kwa3 is: ARGUMENTS
>>> # But note:
>>> show_args('POSITIONAL', 'ARGUMENTS',
kwa1='EXTRA', kwa2='KEYWORD', kwa3='ARGUMENTS',
'EXTRA', 'POSITIONAL', 'ARGUMENTS')
SyntaxError: non-keyword arg after keyword arg
>>>

View file

@ -0,0 +1,10 @@
divide <- function(numerator, denominator) {
numerator / denominator
}
divide(3, 2) # 1.5
divide(numerator=3, denominator=2) # 1.5
divide(n=3, d=2) # 1.5
divide(den=3, num=2) # 0.66
divide(den=3, 2) # 0.66
divide(3, num=2) # 0.66

View file

@ -0,0 +1,76 @@
/*REXX pgm shows named parameters when called as a subroutine/function*/
/*┌────────────────────────────────────────────────────────────────────┐
The syntax of: xxx = func1(parmName2=arg2, parmName1=arg1)
in the REXX language is interpreted specifically as:
xxx = func1( yyy , zzz )
where yyy is the logical result of comparing (the REXX variables)
parmName2 with arg2 and
where zzz is the logical result of comparing (the REXX variables)
parmName1 with arg1
(either as two strings, or arithmetically if both "parmName2" and
"arg2" are both valid REXX numbers. In the REXX language, there
is no way to declare (define) what a variable is [or its type], as
each literal that can be a variable is assumed to be one. If it's
not defined, then its uppercase name is used for the value.
Consider the one-line REXX program: say Where are you?
causes REXX to consider that four-word expression as a "SAY"
statement, followed by three REXX variables, each of which aren't
defined (that is, have a value), so REXX uses a value which is the
uppercased value of the REXX variable name, namely three values in
this case, so the following is displayed: WHERE ARE YOU?
[There is a mechanism in REXX to catch this behavior and raise the
NOVALUE condition.]
To allow a solution to be used for this task's requirement, and
and not get tangled up with the legal REXX syntactical expressions
shown, this REXX programming example uses a variation of the
task's illustration to allow a method in REXX of using named
parameters: xxx = func1('parmName2=' arg2, "parmName1=" arg1)
Also, REXX allows the omitting of arguments by just specifying a
comma (or nothing at all, in the case of a single argument):
xxx = func1(,zzz)
would indicate that the 1st argument has been omitted.
xxx = func1(yyy)
would indicate that the 2nd argument (and all other subsequent
arguments) has/have been omitted.
*/
parse arg count,itemX /*assume 2 values have been used,*/
/*or whatever ... just to show...*/
do j=1 for arg(); _=arg(1) /*now, lets examine each argument*/
if arg(j,'Omitted') then iterate /*skip examining if argJ omitted.*/
/*(above) This is superfluous, */
/* but it demonstrates a method. */
if \arg(j,"Exists") then iterate /*exactly the same as previous. */
/*Only 1st char (2nd arg) is used*/
first=strip(word(_,1)) /*extract the 1st word in arg(j).*/
if right(first,1)\=='=' then iterate /*skip if 1st word isn't: xxx= */
parse var _ varname '= ' value /*parse the named variable &value*/
if varname=='' then iterate /*not the correct format, so skip*/
/*(above) fix this for real pgm. */
call value varname,value /*use BIF to set REXX variable. */
end /*j*/
/* ∙∙∙ perform some REXX magic here with specified parameters and stuff:*/
/* do this, do that, perform dis & dat, compute, gears whiz, cogs */
/* turn, wheels spin, belts move, things get assigned, stuff gets */
/* computed, wheels spin, belts move, things get assigned, motors*/
/* humm, engines roar, coal gets burned, water turns to steam, real */
/* work (some of it useful) gets done, and something is produced. */
return 'the final meaning of life, or 42 --- whichever is appropriate.'
/*stick a fork in it, we're done.*/

View file

@ -0,0 +1,21 @@
/* REXX ---------------------------------------------------------------
* 01.07.2014 Walter Pachl
* Argument values must not start with 'arg'
*--------------------------------------------------------------------*/
x=f(2,3)
Say x
Say ''
y=f('arg2='3,'arg1='2)
Say y
Exit
f: Procedure
Parse Arg p1,p2
Do i=1 to arg()
If left(arg(i),3)='arg' Then
Parse Value arg(i) With 'arg' j '=' p.j
Else p.i=arg(i)
End
Do i=1 To arg()
Say 'p.'i'='p.i
End
Return p.1**p.2

View file

@ -0,0 +1,12 @@
#lang racket
(define (pizza sauce
;; mandatory keyword argument
#:topping topping
;; optional keyword argument with default
#:type [type "deep dish"])
(printf "~a pizza with ~a sauce topped with ~a~n"
type sauce topping))
(pizza "tomato" #:topping "onion")
(pizza #:topping "onion" "garlic" #:type "pan")

View file

@ -0,0 +1,3 @@
sub funkshun ($a, $b?, $c = 15, :$d, *@e, *%f) {
...
}

View file

@ -0,0 +1,11 @@
sub funkshun ($a, $b?, :$c = 15, :$d, *@e, *%f) {
say "$a $b $c $d";
say join ' ', @e;
say join ' ', keys %f;
}
# this particularly thorny call:
funkshun
'Alfa', k1 => 'v1', c => 'Charlie', 'Bravo', 'e1',
d => 'Delta', 'e2', k2 => 'v2';

View file

@ -0,0 +1,6 @@
def example(foo: 0, bar: 1, grill: "pork chops")
puts "foo is #{foo}, bar is #{bar}, and grill is #{grill}"
end
# Note that :foo is omitted and :grill precedes :bar
example(grill: "lamb kebab", bar: 3.14)

View file

@ -0,0 +1,11 @@
def example(opts = {})
# Hash#merge raises TypeError if _opts_ is not a Hash.
# Nothing checks if _opts_ contains unknown keys.
defaults = {foo: 0, bar: 1, grill: "pork chops"}
opts = defaults.merge(opts)
printf("foo is %s, bar is %s, and grill is %s\n",
opts[:foo], opts[:bar], opts[:grill])
end
example(grill: "lamb kebab", bar: 3.14)

View file

@ -0,0 +1 @@
def add(x: Int, y: Int = 1) = x + y

View file

@ -0,0 +1,5 @@
scala> add(5)
6
scala> add(y=10, x=4)
14

View file

@ -0,0 +1,21 @@
(define (keyarg-parser argdefs args kont)
(apply kont
(map (lambda (argdef)
(let loop ((args args))
(cond ((null? args)
(cadr argdef))
((eq? (car argdef) (car args))
(cadr args))
(else
(loop (cdr args))))))
argdefs)))
(define (print-name . args)
(keyarg-parser '((first #f)(last "?"))
args
(lambda (first last)
(display last)
(cond (first
(display ", ")
(display first)))
(newline))))

View file

@ -0,0 +1,8 @@
=> (print-name)
?
=> (print-name 'first "John")
?, John
=>(print-name 'first "John" 'last "Doe")
Doe, John
=>(print-name 'last "Doe")
Doe

Some files were not shown because too many files have changed in this diff Show more