all tasks

This commit is contained in:
Ingy döt Net 2013-04-11 01:07:29 -07:00
parent b83f433714
commit 68f8f3e56b
14735 changed files with 178959 additions and 0 deletions

View file

@ -0,0 +1,4 @@
Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as [[wp:Variadic_function|Variadic Functions]].
Related: [[Call a function]]

View file

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

View file

@ -0,0 +1,8 @@
(defun print-all-fn (xs)
(if (endp xs)
nil
(prog2$ (cw "~x0~%" (first xs))
(print-all-fn (rest xs)))))
(defmacro print-all (&rest args)
`(print-all-fn (quote ,args)))

View file

@ -0,0 +1,17 @@
main:(
MODE STRINT = UNION(STRING, INT, PROC(REF FILE)VOID, VOID);
PROC print strint = (FLEX[]STRINT argv)VOID: (
FOR i TO UPB argv DO
CASE argv[i] IN
(INT i):print(whole(i,-1)),
(STRING s):print(s),
(PROC(REF FILE)VOID f):f(stand out),
(VOID):print(error char)
ESAC;
IF i NE UPB argv THEN print((" ")) FI
OD
);
print strint(("Mary","had",1,"little",EMPTY,new line))
)

View file

@ -0,0 +1,11 @@
function f(a, b, c){
if (a != "") print a
if (b != "") print b
if (c != "") print c
}
BEGIN {
print "[1 arg]"; f(1)
print "[2 args]"; f(1, 2)
print "[3 args]"; f(1, 2, 3)
}

View file

@ -0,0 +1,13 @@
function f(a, b, c) {
if (a != "") print a
if (b != "") print b
if (c != "") print c
}
BEGIN {
# Set ary[1] and ary[2] at runtime.
split("Line 1:Line 2", ary, ":")
# Pass to f().
f(ary[1], ary[2], ary[3])
}

View file

@ -0,0 +1,9 @@
function g(len, ary, i) {
for (i = 1; i <= len; i++) print ary[i];
}
BEGIN {
c = split("Line 1:Line 2:Next line is empty::Last line", a, ":")
g(c, a) # Pass a[1] = "Line 1", a[4] = "", ...
}

View file

@ -0,0 +1,5 @@
public function printArgs(... args):void
{
for (var i:int = 0; i < args.length; i++)
trace(args[i]);
}

View file

@ -0,0 +1,30 @@
with Ada.Strings.Unbounded, Ada.Text_IO;
procedure Variadic is
subtype U_String is Ada.Strings.Unbounded.Unbounded_String;
use type U_String;
function "+"(S: String) return U_String
renames Ada.Strings.Unbounded.To_Unbounded_String;
function "-"(U: U_String) return String
renames Ada.Strings.Unbounded.To_String;
type Variadic_Array is array(Positive range <>) of U_String;
procedure Print_Line(Params: Variadic_Array) is
begin
for I in Params'Range loop
Ada.Text_IO.Put(-Params(I));
if I < Params'Last then
Ada.Text_IO.Put(" ");
end if;
end loop;
Ada.Text_IO.New_Line;
end Print_Line;
begin
Print_Line((+"Mary", +"had", +"a", +"little", +"lamb.")); -- print five strings
Print_Line((1 => +"Rosetta Code is cooool!")); -- print one string
end;

View file

@ -0,0 +1,5 @@
printAll(args*) {
for k,v in args
t .= v "`n"
MsgBox, %t%
}

View file

@ -0,0 +1,3 @@
printAll(4, 3, 5, 6, 4, 3)
printAll(4, 3, 5)
printAll("Rosetta", "Code", "Is", "Awseome!")

View file

@ -0,0 +1,2 @@
args := ["Rosetta", "Code", "Is", "Awseome!"]
printAll(args*)

View file

@ -0,0 +1,13 @@
string = Mary had a little lamb
StringSplit, arg, string, %A_Space%
Function(arg1,arg2,arg3,arg4,arg5) ;Calls the function with 5 arguments.
Function() ;Calls the function with no arguments.
return
Function(arg1="",arg2="",arg3="",arg4="",arg5="") {
Loop,5
If arg%A_Index% !=
out .= arg%A_Index% "`n"
MsgBox,% out ? out:"No non-blank arguments were passed."
}

View file

@ -0,0 +1,12 @@
SUB printAll cdecl (count As Integer, ... )
DIM arg AS Any Ptr
DIM i AS Integer
arg = va_first()
FOR i = 1 To count
PRINT va_arg(arg, Double)
arg = va_next(arg, Double)
NEXT i
END SUB
printAll 3, 3.1415, 1.4142, 2.71828

View file

@ -0,0 +1,21 @@
#include <iostream>
template<typename T>
void print(T const& t)
{
std::cout << t;
}
template<typename First, typename ... Rest>
void print(First const& first, Rest const& ... rest)
{
std::cout << first;
print(rest ...);
}
int main()
{
int i = 10;
std::string s = "Hello world";
print("i = ", i, " and s = \"", s, "\"\n");
}

View file

@ -0,0 +1,13 @@
#include <stdio.h>
#include <stdarg.h>
void varstrings(int count, ...) /* the ellipsis indicates variable arguments */
{
va_list args;
va_start(args, count);
while (count--)
puts(va_arg(args, const char *));
va_end(args);
}
varstrings(5, "Mary", "had", "a", "little", "lamb");

View file

@ -0,0 +1,6 @@
(defn foo [& args]
(doseq [a args]
(println a)))
(foo :bar :baz :quux)
(apply foo [:bar :baz :quux])

View file

@ -0,0 +1,8 @@
(defun example (&rest args)
(dolist (arg args)
(print arg)))
(example "Mary" "had" "a" "little" "lamb")
(let ((args '("Mary" "had" "a" "little" "lamb")))
(apply #'example args))

View file

@ -0,0 +1,23 @@
import std.stdio, std.algorithm;
void printAll(TyArgs...)(TyArgs args) {
foreach (el; args)
writeln(el);
}
// Typesafe variadic function for dynamic array
void showSum1(int[] items...) {
writeln(reduce!q{a + b}(0, items));
}
// Typesafe variadic function for fixed size array
void showSum2(int[4] items...) {
writeln(reduce!q{a + b}(0, items));
}
void main() {
printAll(4, 5.6, "Rosetta", "Code", "is", "awseome");
writeln();
showSum1(1, 3, 50);
showSum2(1, 3, 50, 10);
}

View file

@ -0,0 +1,11 @@
def example {
match [`run`, args] {
for x in args {
println(x)
}
}
}
example("Mary", "had", "a", "little", "lamb")
E.call(example, "run", ["Mary", "had", "a", "little", "lamb"])

View file

@ -0,0 +1,6 @@
def non_example {
to run(x, y) {
println(x)
println(y)
}
}

View file

@ -0,0 +1,4 @@
def non_example(x, y) {
println(x)
println(y)
}

View file

@ -0,0 +1,15 @@
>function allargs () ...
$ loop 1 to argn();
$ args(#),
$ end
$endfunction
>allargs(1,3,"Test",1:2)
1
3
Test
[ 1 2 ]
>function args test (x) := {x,x^2,x^3}
>allargs(test(4))
4
16
64

View file

@ -0,0 +1,8 @@
procedure print_args(sequence args)
for i = 1 to length(args) do
puts(1,args[i])
puts(1,' ')
end for
end procedure
print_args({"Mary", "had", "a", "little", "lamb"})

View file

@ -0,0 +1,2 @@
: sum ( x_1 ... x_n n -- sum ) 1 ?do + loop ;
4 3 2 1 4 sum . \ 10

View file

@ -0,0 +1 @@
: .stack ( -- ) depth 0 ?do i pick . loop ;

View file

@ -0,0 +1,33 @@
program varargs
integer, dimension(:), allocatable :: va
integer :: i
! using an array (vector) static
call v_func()
call v_func( (/ 100 /) )
call v_func( (/ 90, 20, 30 /) )
! dynamically creating an array of 5 elements
allocate(va(5))
va = (/ (i,i=1,5) /)
call v_func(va)
deallocate(va)
contains
subroutine v_func(arglist)
integer, dimension(:), intent(in), optional :: arglist
integer :: i
if ( present(arglist) ) then
do i = lbound(arglist, 1), ubound(arglist, 1)
print *, arglist(i)
end do
else
print *, "no argument at all"
end if
end subroutine v_func
end program varargs

View file

@ -0,0 +1,6 @@
func printAll(things ... string) {
// it's as if you declared "things" as a []string, containing all the arguments
for _, x := range things {
fmt.Println(x)
}
}

View file

@ -0,0 +1,2 @@
args := []string{"foo", "bar"}
printAll(args...)

View file

@ -0,0 +1,3 @@
def printAll( Object[] args) { args.each{ arg -> println arg } }
printAll(1, 2, "three", ["3", "4"])

View file

@ -0,0 +1,17 @@
class PrintAllType t where
process :: [String] -> t
instance PrintAllType (IO a) where
process args = do mapM_ putStrLn args
return undefined
instance (Show a, PrintAllType r) => PrintAllType (a -> r) where
process args = \a -> process (args ++ [show a])
printAll :: (PrintAllType t) => t
printAll = process []
main :: IO ()
main = do printAll 5 "Mary" "had" "a" "little" "lamb"
printAll 4 3 5
printAll "Rosetta" "Code" "Is" "Awseome!"

View file

@ -0,0 +1,9 @@
procedure main ()
varargs("some", "extra", "args")
write()
varargs ! ["a","b","c","d"]
end
procedure varargs(args[])
every write(!args)
end

View file

@ -0,0 +1 @@
printAll := method(call message arguments foreach(println))

View file

@ -0,0 +1,6 @@
A=:2
B=:3
C=:5
sum=:+/
sum 1,A,B,4,C
15

View file

@ -0,0 +1,3 @@
commaAnd=: [: ; (<' and ') _2} ::] 1 }.&, (<', ') ,. ":each
commaAnd 'dog';A;B;'cat';C
dog, 2, 3, cat and 5

View file

@ -0,0 +1,6 @@
public static void printAll(Object... things){
// "things" is an Object[]
for(Object i:things){
System.out.println(i);
}
}

View file

@ -0,0 +1,3 @@
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awseome!");

View file

@ -0,0 +1,2 @@
Object[] args = {"Rosetta", "Code", "Is", "Awseome!"};
printAll(args);

View file

@ -0,0 +1,3 @@
Object[] args = {"Rosetta", "Code", "Is", "Awseome,"};
printAll(args, "Dude!");//does not print "Rosetta Code Is Awesome, Dude!"
//instead prints the type and hashcode for args followed by "Dude!"

View file

@ -0,0 +1 @@
printAll((Object)args);

View file

@ -0,0 +1,7 @@
function printAll() {
for (var i=0; i<arguments.length; i++)
print(arguments[i])
}
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awseome!");

View file

@ -0,0 +1,2 @@
args = ["Rosetta", "Code", "Is", "Awseome!"]
printAll.apply(null, args)

View file

@ -0,0 +1 @@
bar(a,b,x...) = (a,b,x)

View file

@ -0,0 +1,11 @@
julia> bar(1,2)
(1,2,())
julia> bar(1,2,3)
(1,2,(3,))
julia> bar(1,2,3,4)
(1,2,(3,4))
julia> bar(1,2,3,4,5,6)
(1,2,(3,4,5,6))

View file

@ -0,0 +1,5 @@
julia> x = (3,4)
(3,4)
julia> bar(1,2,x...)
(1,2,(3,4))

View file

@ -0,0 +1,11 @@
julia> x = (2,3,4)
(2,3,4)
julia> bar(1,x...)
(1,2,(3,4))
julia> x = (1,2,3,4)
(1,2,3,4)
julia> bar(x...)
(1,2,(3,4))

View file

@ -0,0 +1,17 @@
julia> x = [3,4]
2-element Int64 Array:
3
4
julia> bar(1,2,x...)
(1,2,(3,4))
julia> x = [1,2,3,4]
4-element Int64 Array:
1
2
3
4
julia> bar(x...)
(1,2,(3,4))

View file

@ -0,0 +1,17 @@
baz(a,b) = a + b
julia> args = [1,2]
2-element Int64 Array:
1
2
julia> baz(args...)
3
julia> args = [1,2,3]
3-element Int64 Array:
1
2
3
julia> baz(args...)

View file

@ -0,0 +1,6 @@
to varargs [:args]
foreach :args [print ?]
end
(varargs "Mary "had "a "little "lamb)
apply "varargs [Mary had a little lamb]

View file

@ -0,0 +1,3 @@
function varar(...)
for i, v in ipairs{...} do print(v) end
end

View file

@ -0,0 +1,10 @@
define(`showN',
`ifelse($1,0,`',`$2
$0(decr($1),shift(shift($@)))')')dnl
define(`showargs',`showN($#,$@)')dnl
dnl
showargs(a,b,c)
dnl
define(`x',`1,2')
define(`y',`,3,4,5')
showargs(x`'y)

View file

@ -0,0 +1,7 @@
function variadicFunction(varargin)
for i = (1:numel(varargin))
disp(varargin{i});
end
end

View file

@ -0,0 +1,10 @@
>> variadicFunction(1,2,3,4,'cat')
1
2
3
4
cat

View file

@ -0,0 +1 @@
ShowMultiArg[x___] := Do[Print[i], {i, {x}}]

View file

@ -0,0 +1,3 @@
ShowMultiArg[]
ShowMultiArg[a, b, c]
ShowMultiArg[5, 3, 1]

View file

@ -0,0 +1,9 @@
[nothing]
a
b
c
5
3
1

View file

@ -0,0 +1,10 @@
show([L]) := block([n], n: length(L), for i from 1 thru n do disp(L[i]))$
show(1, 2, 3, 4);
apply(show, [1, 2, 3, 4]);
/* Actually, the built-in function "disp" is already what we want */
disp(1, 2, 3, 4);
apply(disp, [1, 2, 3, 4]);

View file

@ -0,0 +1,14 @@
ddef print_arg(text t) =
for x = t:
if unknown x: message "unknown value"
elseif numeric x: message decimal x
elseif string x: message x
elseif path x: message "a path"
elseif pair x: message decimal (xpart(x)) & ", " & decimal (ypart(x))
elseif boolean x: if x: message "true!" else: message "false!" fi
elseif pen x: message "a pen"
elseif picture x: message "a picture"
elseif transform x: message "a transform" fi; endfor enddef;
print_arg("hello", x, 12, fullcircle, currentpicture, down, identity, false, pencircle);
end

View file

@ -0,0 +1,16 @@
MODULE Varargs EXPORTS Main;
IMPORT IO;
VAR strings := ARRAY [1..5] OF TEXT {"foo", "bar", "baz", "quux", "zeepf"};
PROCEDURE Variable(VAR arr: ARRAY OF TEXT) =
BEGIN
FOR i := FIRST(arr) TO LAST(arr) DO
IO.Put(arr[i] & "\n");
END;
END Variable;
BEGIN
Variable(strings);
END Varargs.

View file

@ -0,0 +1,26 @@
MODULE Varargs EXPORTS Main;
IMPORT IO, Fmt;
VAR
strings := NEW(REF TEXT);
ints := NEW(REF INTEGER);
reals := NEW(REF REAL);
refarr := ARRAY [1..3] OF REFANY {strings, ints, reals};
PROCEDURE Variable(VAR arr: ARRAY OF REFANY) =
BEGIN
FOR i := FIRST(arr) TO LAST(arr) DO
TYPECASE arr[i] OF
| REF TEXT(n) => IO.Put(n^ & "\n");
| REF INTEGER(n) => IO.Put(Fmt.Int(n^) & "\n");
| REF REAL(n) => IO.Put(Fmt.Real(n^) & "\n");
ELSE (* skip *)
END;
END;
END Variable;
BEGIN
strings^ := "Rosetta"; ints^ := 1; reals^ := 3.1415;
Variable(refarr);
END Varargs.

View file

@ -0,0 +1,17 @@
#include <stdarg.h>
void logObjects(id firstObject, ...) // <-- there is always at least one arg, "nil", so this is valid, even for "empty" list
{
va_list args;
va_start(args, firstObject);
id obj;
for (obj = firstObject; obj != nil; obj = va_arg(args, id))
NSLog(@"%@", obj);
va_end(args);
}
// This function can be called with any number or type of objects, as long as you terminate it with "nil":
logObjects(@"Rosetta", @"Code", @"Is", @"Awseome!", nil);
logObjects([NSNumber numberWithInt:4],
[NSNumber numberWithInt:3],
@"foo", nil);

View file

@ -0,0 +1,12 @@
declare
class Demo from BaseObject
meth test(...)=Msg
{Record.forAll Msg Show}
end
end
D = {New Demo noop}
Constructed = {List.toTuple test {List.number 1 10 1}}
in
{D test(1 2 3 4)}
{D Constructed}

View file

@ -0,0 +1,11 @@
function printAll() {
foreach (func_get_args() as $x) // first way
echo "$x\n";
$numargs = func_num_args(); // second way
for ($i = 0; $i < $numargs; $i++)
echo func_get_arg($i), "\n";
}
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll("Rosetta", "Code", "Is", "Awseome!");

View file

@ -0,0 +1,2 @@
$args = array("Rosetta", "Code", "Is", "Awseome!");
call_user_func_array('printAll', $args);

View file

@ -0,0 +1,9 @@
/* PL/I permits optional arguments, but not an infinitely varying */
/* argument list: */
s: procedure (a, b, c, d);
declare (a, b, c, d, e) float optional;
if ^omitted(a) then put skip list (a);
if ^omitted(b) then put skip list (b);
if ^omitted(c) then put skip list (c);
if ^omitted(d) then put skip list (d);
end s;

View file

@ -0,0 +1,7 @@
sub foo {
.say for @_;
say .key, ': ', .value for %_;
}
foo 1, 2, command => 'buckle my shoe',
3, 4, order => 'knock at the door';

View file

@ -0,0 +1,4 @@
sub foo (*@positional, *%named) {
.say for @positional;
say .key, ': ', .value for %named;
}

View file

@ -0,0 +1 @@
foo |@ary, |%hsh;

View file

@ -0,0 +1,5 @@
sub print_all {
foreach (@_) {
print "$_\n";
}
}

View file

@ -0,0 +1,3 @@
print_all(4, 3, 5, 6, 4, 3);
print_all(4, 3, 5);
print_all("Rosetta", "Code", "Is", "Awseome!");

View file

@ -0,0 +1,2 @@
@args = ("Rosetta", "Code", "Is", "Awseome!");
print_all(@args);

View file

@ -0,0 +1,3 @@
(de varargs @
(while (args)
(println (next)) ) )

View file

@ -0,0 +1,5 @@
(de varargs (Arg1 Arg2 . @)
(println Arg1)
(println Arg2)
(while (args)
(println (next)) ) )

View file

@ -0,0 +1 @@
(varargs 'a 123 '(d e f) "hello")

View file

@ -0,0 +1 @@
(apply varargs '(a 123 (d e f) "hello"))

View file

@ -0,0 +1,5 @@
function print_all {
foreach ($x in $args) {
Write-Host $x
}
}

View file

@ -0,0 +1 @@
print_all 1 2 'foo'

View file

@ -0,0 +1,2 @@
$array = 1,2,'foo'
Invoke-Expression "& print_all $array"

View file

@ -0,0 +1 @@
print_all @array

View file

@ -0,0 +1,3 @@
def print_all(*things):
for x in things:
print x

View file

@ -0,0 +1,3 @@
print_all(4, 3, 5, 6, 4, 3)
print_all(4, 3, 5)
print_all("Rosetta", "Code", "Is", "Awseome!")

View file

@ -0,0 +1,2 @@
args = ["Rosetta", "Code", "Is", "Awseome!"]
print_all(*args)

View file

@ -0,0 +1,25 @@
>>> def printargs(*positionalargs, **keywordargs):
print "POSITIONAL ARGS:\n " + "\n ".join(repr(x) for x in positionalargs)
print "KEYWORD ARGS:\n " + '\n '.join(
"%r = %r" % (k,v) for k,v in keywordargs.iteritems())
>>> printargs(1,'a',1+0j, fee='fi', fo='fum')
POSITIONAL ARGS:
1
'a'
(1+0j)
KEYWORD ARGS:
'fee' = 'fi'
'fo' = 'fum'
>>> alist = [1,'a',1+0j]
>>> adict = {'fee':'fi', 'fo':'fum'}
>>> printargs(*alist, **adict)
POSITIONAL ARGS:
1
'a'
(1+0j)
KEYWORD ARGS:
'fee' = 'fi'
'fo' = 'fum'
>>>

View file

@ -0,0 +1,8 @@
(define varargs-func
A -> (print A))
(define varargs
[varargs | Args] -> [varargs-func [list | Args]]
A -> A)
(sugar in varargs 1)

View file

@ -0,0 +1,10 @@
printallargs1 <- function(...) list(...)
printallargs1(1:5, "abc", TRUE)
# [[1]]
# [1] 1 2 3 4 5
#
# [[2]]
# [1] "abc"
#
# [[3]]
# [1] TRUE

View file

@ -0,0 +1,10 @@
printallargs2 <- function(...)
{
args <- list(...)
lapply(args, print)
invisible()
}
printallargs2(1:5, "abc", TRUE)
# [1] 1 2 3 4 5
# [1] "abc"
# [1] TRUE

View file

@ -0,0 +1,2 @@
arglist <- list(x=runif(10), trim=0.1, na.rm=TRUE)
do.call(mean, arglist)

View file

@ -0,0 +1,11 @@
REBOL [
Title: "Variadic Arguments"
]
print-all: func [
args [block!] {the arguments to print}
] [
foreach arg args [print arg]
]
print-all [rebol works this way]

View file

@ -0,0 +1,5 @@
print_all: procedure
do j=1 for arg()
say arg(j)
end /*j*/
return

View file

@ -0,0 +1,5 @@
print_all: procedure
do j=1 for arg()
say '[argument' j"]: " arg(j)
end /*j*/
return

View file

@ -0,0 +1,10 @@
call print_all .1,5,2,4,-3, 4.7e1, 013.000 ,, 8**2 -3, sign(-66), abs(-71.00), 1 || 1, 'seven numbers are prime, 8th is null'
call print_all "Hello", "World", "Bang", "Slash-N"
call print_all "One ringy-dingy,",
"two ringy-dingy,",
"three ringy-dingy...",
"Hello? This is Ma Bell.",
"Have you been misusing your instrument?",
"(Lily Tomlin routine)" /*example showing multi-line arguments.*/

View file

@ -0,0 +1,12 @@
SUBI printAll (...)
FOR i = 1 TO ParamValCount
PRINT ParamVal(i)
NEXT i
FOR i = 1 TO ParamStrCount
PRINT ParamStr$(i)
NEXT i
END SUBI
printAll 4, 3, 5, 6, 4, 3
printAll 4, 3, 5
printAll "Rosetta", "Code", "Is", "Awseome!"

View file

@ -0,0 +1,3 @@
def print_all(*things)
things.each { |x| puts x }
end

View file

@ -0,0 +1,3 @@
print_all(4, 3, 5, 6, 4, 3)
print_all(4, 3, 5)
print_all("Rosetta", "Code", "Is", "Awseome!")

View file

@ -0,0 +1,2 @@
args = ["Rosetta", "Code", "Is", "Awseome!"]
print_all(*args)

View file

@ -0,0 +1 @@
def printAll(args: Any*) = args foreach println

View file

@ -0,0 +1,4 @@
(define (print-all . things)
(for-each
(lambda (x) (display x) (newline))
things))

View file

@ -0,0 +1,5 @@
(define print-all
(lambda things
(for-each
(lambda (x) (display x) (newline))
things)))

View file

@ -0,0 +1,3 @@
(print-all 4 3 5 6 4 3)
(print-all 4 3 5)
(print-all "Rosetta" "Code" "Is" "Awseome!")

View file

@ -0,0 +1,2 @@
(define args '("Rosetta" "Code" "Is" "Awseome!"))
(apply print-all args)

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