tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,13 @@
{{omit from|BBC BASIC}}
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 f 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]]

View file

@ -0,0 +1,2 @@
---
note: Basic language learning

View file

@ -0,0 +1,28 @@
#!/usr/local/bin/a68g --script #
MODE OPTNAME = STRUCT(STRING name),
OPTSPECIES = STRUCT(STRING species),
OPTBREED = STRUCT(STRING breed),
OWNER=STRUCT(STRING first name, middle name, last name);
# due to the Yoneda ambiguity simple arguments must have an unique operator defined #
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 = ([]UNION(OPTNAME,OPTSPECIES,OPTBREED,OWNER) 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;
printf(($gx$,"Details: a",breed,species,"named",name,"owned by",owner,$l$))
);
print pet((NAME "Mike", SPECIES "Dog", BREED "Irish Setter", OWNER("Harry", "S.", "Truman")));
print pet(())

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,9 @@
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
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,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,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,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,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,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,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,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,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,7 @@
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}]
->9
fn[3,4,{Offset->2,Add->True}]
->9

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,6 @@
# 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 : Object {
// 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,3 @@
sub funkshun ($a, $b?, $c = 15, :$d, *@e, *%f) {
...
}

View file

@ -0,0 +1,5 @@
sub funkshun ($a, $b?, $c = 15, :$d, *@e, *%f) {
say "$a $b $c $d";
say join ' ', @e;
say join ' ', keys %f;
}

View file

@ -0,0 +1,3 @@
funkshun
'Alfa', k1 => 'v1', c => 'Charlie', 'Bravo', 'e1',
d => 'Delta', 'e2', k2 => 'v2';

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.
exists $h{verbosity}
and print "Verbosity specified as $h{verbosity}.\n";
# 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,3 @@
funkshun
verbosity => 3, password => 'foobie blech',
extra_lives => 3, '42' => 'answer', password => 'joshua';

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,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,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,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,8 @@
def example(opts = {})
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

View file

@ -0,0 +1,9 @@
Object subclass: AnotherClass [
"..."
initWithArray: anArray [ "single argument" ]
initWithArray: anArray andString: aString [
"two args; these two methods in usage resemble
a named argument, with optional andString argument"
]
"..."
]

View file

@ -0,0 +1,6 @@
test = function (one, two, three = '', four = '', five = '')
{
Print('one: ' $ one $ ', two: ' $ two $ ', three: ' $ three $
', four: ' $ four $ ', five: ' $ five)
}
test('1', '2', five: '5', three: '3')

View file

@ -0,0 +1 @@
one: 1, two: 2, three: 3, four: , five: 5

View file

@ -0,0 +1,11 @@
proc example args {
# Set the defaults
array set opts {-foo 0 -bar 1 -grill "hamburger"}
# Merge in the values from the caller
array set opts $args
# Use the arguments
return "foo is $opts(-foo), bar is $opts(-bar), and grill is $opts(-grill)"
}
# Note that -foo is omitted and -grill precedes -bar
example -grill "lamb kebab" -bar 3.14
# => foo is 0, bar is 3.14, and grill is lamb kebab

View file

@ -0,0 +1,18 @@
package require opt
tcl::OptProc example {
{-foo -int 0 "The number of foos"}
{-bar -float 1.0 "How much bar-ness"}
{-grill -any "hamburger" "What to cook on the grill"}
} {
return "foo is $foo, bar is $bar, and grill is $grill"
}
example -grill "lamb kebab" -bar 3.14
# => foo is 0, bar is 3.14, and grill is lamb kebab
example -help
# Usage information:
# Var/FlagName Type Value Help
# ------------ ---- ----- ----
# ( -help gives this help )
# -foo int (0) The number of foos
# -bar float (1.0) How much bar-ness
# -grill any (hamburger) What to cook on the grill

View file

@ -0,0 +1,8 @@
'the function
Sub whatever(foo As Long, bar As Integer, baz As Byte, qux As String)
'...
End Sub
'calling the function -- note the Pascal-style assignment operator
Sub crap()
whatever bar:=1, baz:=2, foo:=-1, qux:="Why is ev'rybody always pickin' on me?"
End Sub

View file

@ -0,0 +1,4 @@
<xsl:template name="table-header">
<xsl:param name="title"/>
...
</xsl:template>