task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Liberty_BASIC
Liberty BASIC
  drive1$ = left$(Drives$,1) run "cmd.exe /";drive1$;" dir & pause"  
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Limbo
Limbo
implement Runls;   include "sys.m"; sys: Sys; include "draw.m"; include "sh.m";   Runls: module { init: fn(ctxt: ref Draw->Context, args: list of string); };   init(ctxt: ref Draw->Context, args: list of string) { sys = load Sys Sys->PATH; ls := load Command "/dis/ls.dis"; if(ls == nil) die("Couldn't load /dis/ls.dis"); ls->init(ctxt, "ls" :: tl args); }   die(s: string) { sys->fprint(sys->fildes(2), "runls: %s: %r", s); raise "fail:errors"; }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Batch_File
Batch File
@echo off set /p x= set /a fs=%x%-1 set y=%x% FOR /L %%a IN (%fs%, -1, 1) DO SET /a y*=%%a if %x% EQU 0 set y=1 echo %y% pause exit
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Prolog
Prolog
:- arithmetic_function((^^)/2). :- op(200, xfy, user:(^^)).
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#PureBasic
PureBasic
Procedure powI(base, exponent) Protected i, result.d If exponent < 0 If base = 1 result = 1 EndIf ProcedureReturn result EndIf result = 1 For i = 1 To exponent result * base Next ProcedureReturn result EndProcedure   Procedure.f powF(base.f, exponent) Protected i, magExponent = Abs(exponent), result.d If base <> 0 result = 1.0 If exponent <> 0 For i = 1 To magExponent result * base Next If exponent < 0 result = 1.0 / result EndIf EndIf EndIf ProcedureReturn result EndProcedure   If OpenConsole() Define x, a.f, exp   x = Random(10) - 5 a = Random(10000) / 10000 * 10 For exp = -3 To 3 PrintN(Str(x) + " ^ " + Str(exp) + " = " + Str(powI(x, exp))) PrintN(StrF(a) + " ^ " + Str(exp) + " = " + StrF(powF(a, exp))) PrintN("--------------") Next   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole() EndIf
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#SNOBOL4
SNOBOL4
I = 1 LOOP FIZZBUZZ = "" EQ(REMDR(I, 3), 0)  :F(TRY_5) FIZZBUZZ = FIZZBUZZ "FIZZ" TRY_5 EQ(REMDR(I, 5), 0)  :F(DO_NUM) FIZZBUZZ = FIZZBUZZ "BUZZ" DO_NUM IDENT(FIZZBUZZ, "")  :F(SHOW) FIZZBUZZ = I SHOW OUTPUT = FIZZBUZZ I = I + 1 LE(I, 100)  :S(LOOP) END
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Delphi
Delphi
  program Execute_Brain;   {$APPTYPE CONSOLE}   uses Winapi.Windows, System.SysUtils;   const DataSize = 1024; // Size of Data segment MaxNest = 1000; // Maximum nesting depth of []   function Readkey: Char; var InputRec: TInputRecord; NumRead: Cardinal; KeyMode: DWORD; StdIn: THandle; begin StdIn := GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(StdIn, KeyMode); SetConsoleMode(StdIn, 0);   repeat ReadConsoleInput(StdIn, InputRec, 1, NumRead); if (InputRec.EventType and KEY_EVENT <> 0) and InputRec.Event.KeyEvent.bKeyDown then begin if InputRec.Event.KeyEvent.AsciiChar <> #0 then begin Result := InputRec.Event.KeyEvent.UnicodeChar; Break; end; end; until FALSE;   SetConsoleMode(StdIn, KeyMode); end;   procedure ExecuteBF(Source: string); var Dp: pByte; // Used as the Data Pointer DataSeg: Pointer; // Start of the DataSegment (Cell 0) Ip: pChar; // Used as instruction Pointer LastIp: Pointer; // Last adr of code. JmpStack: array[0..MaxNest - 1] of pChar; // Stack to Keep track of active "[" locations JmpPnt: Integer; // Stack pointer ^^ JmpCnt: Word; // Used to count brackets when skipping forward.   begin   // Set up then data segment getmem(DataSeg, dataSize); Dp := DataSeg; // fillbyte(dp^,dataSize,0); FillChar(Dp^, DataSize, 0);   // Set up the JmpStack JmpPnt := -1;   // Set up Instruction Pointer Ip := @Source[1]; LastIp := @Source[length(Source)]; if Ip = nil then exit;   // Main Execution loop repeat { until Ip > LastIp } case Ip^ of '<': dec(Dp); '>': inc(Dp); '+': inc(Dp^); '-': dec(Dp^); '.': write(chr(Dp^)); ',': Dp^ := ord(ReadKey); '[': if Dp^ = 0 then begin // skip forward until matching bracket; JmpCnt := 1; while (JmpCnt > 0) and (Ip <= LastIp) do begin inc(Ip); case Ip^ of '[': inc(JmpCnt); ']': dec(JmpCnt); #0: begin Writeln('Error brackets don''t match'); halt; end; end; end; end else begin // Add location to Jump stack inc(JmpPnt); JmpStack[JmpPnt] := Ip; end; ']': if Dp^ > 0 then // Jump Back to matching [ Ip := JmpStack[JmpPnt] else // Remove Jump from stack dec(JmpPnt); end; inc(Ip); until Ip > LastIp; freemem(DataSeg, dataSize); end;   const HelloWorldWiki = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>' + '---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'; pressESCtoCont = '>[-]+++++++[<++++++++++>-]<->>[-]+++++++[<+++++++++++' + '+>-]<->>[-]++++[<++++++++>-]+>[-]++++++++++[<++++++++' + '++>-]>[-]++++++++[<++++++++++++++>-]<.++.+<.>..<<.<<.' + '-->.<.>>.>>+.-----.<<.[<<+>>-]<<.>>>>.-.++++++.<++++.' + '+++++.>+.<<<<++.>+[>+<--]>++++...'; waitForEsc = '[-]>[-]++++[<+++++++>-]<->[-]>+[[-]<<[>+>+<<-]' + '>>[<' + '<+>>-],<[->-<]>]';   begin // Execute "Hello World" example from Wikipedia ExecuteBF(HelloWorldWiki);   // Print text "press ESC to continue....." and wait for ESC to be pressed ExecuteBF(pressESCtoCont + waitForEsc); end.
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Erlang
Erlang
-module(evolution). -export([run/0]).   -define(MUTATE, 0.05). -define(POPULATION, 100). -define(TARGET, "METHINKS IT IS LIKE A WEASEL"). -define(MAX_GENERATIONS, 1000).   run() -> evolve_gens().   evolve_gens() -> Initial = random_string(length(?TARGET)), evolve_gens(Initial,0,fitness(Initial)). evolve_gens(Parent,Generation,0) -> io:format("Generation[~w]: Achieved the target: ~s~n",[Generation,Parent]); evolve_gens(Parent,Generation,_Fitness) when Generation == ?MAX_GENERATIONS -> io:format("Reached Max Generations~nFinal string is ~s~n",[Parent]); evolve_gens(Parent,Generation,Fitness) -> io:format("Generation[~w]: ~s, Fitness: ~w~n", [Generation,Parent,Fitness]), Child = evolve_string(Parent), evolve_gens(Child,Generation+1,fitness(Child)).   fitness(String) -> fitness(String, ?TARGET). fitness([],[]) -> 0; fitness([H|Rest],[H|Target]) -> fitness(Rest,Target); fitness([_H|Rest],[_T|Target]) -> 1+fitness(Rest,Target).   mutate(String) -> mutate(String,[]). mutate([],Acc) -> lists:reverse(Acc); mutate([H|T],Acc) -> case random:uniform() < ?MUTATE of true -> mutate(T,[random_character()|Acc]); false -> mutate(T,[H|Acc]) end.   evolve_string(String) -> evolve_string(String,?TARGET,?POPULATION,String). evolve_string(_,_,0,Child) -> Child; evolve_string(Parent,Target,Population,Best_Child) -> Child = mutate(Parent), case fitness(Child) < fitness(Best_Child) of true -> evolve_string(Parent,Target,Population-1,Child); false -> evolve_string(Parent,Target,Population-1,Best_Child) end.   random_character() -> case random:uniform(27)-1 of 26 -> $ ; R -> $A+R end.   random_string(Length) -> random_string(Length,[]). random_string(0,Acc) -> Acc; random_string(N,Acc) when N > 0 -> random_string(N-1,[random_character()|Acc]).    
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Luck
Luck
function fib(x: int): int = ( let cache = {} in let fibc x = if x<=1 then x else ( if x not in cache then cache[x] = fibc(x-1) + fibc(x-2); cache[x] ) in fibc(x) );; for x in range(10) do print(fib(x))
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Tcl
Tcl
import "os" for Process   var hq9plus = Fn.new { |code| var acc = 0 var sb = "" for (c in code) { if (c == "h" || c == "H") { sb = sb + "Hello, world!\n" } else if (c == "q" || c == "Q") { sb = sb + code + "\n" } else if (c == "9") { for (i in 99..1) { var s = (i > 1) ? "s" : "" sb = sb + "%(i) bottle%(s) of beer on the wall\n" sb = sb + "%(i) bottle%(s) of beer\n" sb = sb + "Take one down, pass it around\n" } sb = sb + "No more bottles of beer on the wall!\n" } else if (c == "+") { acc = acc + 1 } else { Fiber.abort("Code contains illegal operation '%(c)'") } } System.print(sb) }   var args = Process.arguments if (args.count != 1) { System.print("Please pass in the HQ9+ code to be executed.") } else { hq9plus.call(args[0]) }
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>] There is one rule per line. If there is a   .   (period)   present before the   <replacement>,   then this is a terminating rule in which case the interpreter must halt execution. A ruleset consists of a sequence of rules, with optional comments. Rulesets Use the following tests on entries: Ruleset 1 # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate the output: I bought a bag of apples from my brother. Ruleset 2 A test of the terminating rule # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate: I bought a bag of apples from T shop. Ruleset 3 This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped. # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As W my Bgage from T S. Should generate: I bought a bag of apples with my money from T shop. Ruleset 4 This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.) ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> Sample text of: _1111*11111_ should generate the output: 11111111111111111111 Ruleset 5 A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s,   the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets. # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 This ruleset should turn 000000A000000 into 00011H1111000
#Scheme
Scheme
  (define split-into-lines (lambda (str) (let loop ((index 0) (result '())) (let ((next-index (string-index str #\newline index))) (if next-index (loop (+ next-index 1) (cons (substring str index next-index) result)) (reverse (cons (substring str index) result)))))))   (define parse-rules (lambda (str) (let loop ((rules (split-into-lines str)) (result '())) (if (null? rules) (reverse result) (let ((rule (car rules))) (loop (cdr rules) (if (or (string=? rule "") (eq? (string-ref rule 0) #\#)) result (cons (let ((index (string-contains rule "->" 1))) (list (string-trim-right (substring rule 0 index)) (string-trim (substring rule (+ index 2))))) result))))))))     (define apply-rules (lambda (str rules) (let loop ((remaining rules) (result str)) (if (null? remaining) result (let* ((rule (car remaining)) (pattern (car rule)) (replacement (cadr rule)) (start (string-contains result pattern))) (if start (if (eq? #\. (string-ref replacement 0)) (string-replace result replacement start (+ start (string-length pattern)) 1) (apply-rules (string-replace result replacement start (+ start (string-length pattern))) rules)) (loop (cdr remaining) result)))))))  
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Pascal
Pascal
# throw an exception die "Danger, danger, Will Robinson!";   # catch an exception and show it eval { die "this could go wrong mightily"; }; print $@ if $@;   # rethrow die $@;
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Perl
Perl
# throw an exception die "Danger, danger, Will Robinson!";   # catch an exception and show it eval { die "this could go wrong mightily"; }; print $@ if $@;   # rethrow die $@;
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Lingo
Lingo
sx = xtra("Shell").new() if the platform contains "win" then put sx.shell_cmd("dir") else put sx.shell_cmd("ls") end if
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Locomotive_Basic
Locomotive Basic
LIST
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Logo
Logo
print first butfirst shell [ls -a]  ; ..
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#BBC_BASIC
BBC BASIC
*FLOAT64 @% = &1010   PRINT FNfactorial(18) END   DEF FNfactorial(n) IF n <= 1 THEN = 1 ELSE = n * FNfactorial(n-1)
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Python
Python
MULTIPLY = lambda x, y: x*y   class num(float): # the following method has complexity O(b) # rather than O(log b) via the rapid exponentiation def __pow__(self, b): return reduce(MULTIPLY, [self]*b, 1)   # works with ints as function or operator print num(2).__pow__(3) print num(2) ** 3   # works with floats as function or operator print num(2.3).__pow__(8) print num(2.3) ** 8
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   forward is ** ( n n --> n )   [ dup 1 < iff [ 2drop 1 ] done dup 1 & iff [ 1 - dip dup ** * ] else [ 1 >> dip [ dup * ] ** ] ] resolves ** ( n n --> n )   forward is (v**) ( n/d n --> n/d )   [ dup 0 = iff [ drop 2drop 1 n->v ] done dup 1 & iff [ 1 - dip 2dup (v**) v* ] else [ 1 >> dip [ 2dup v* ] (v**) ] ] resolves (v**) ( n/d n --> n/d )   [ dup 0 < iff [ abs (v**) 1/v ] else (v**) ] is v** ( n/d n --> n/d )   say "The 10th power of 2 is: " 2 10 ** echo cr cr   say "The -10th power of 2.5 is: " $ "2.5" $->v drop -10 v** 20 point$ echo$
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#SNUSP
SNUSP
SELECT CASE WHEN MOD(level,15)=0 THEN 'FizzBuzz' WHEN MOD(level,3)=0 THEN 'Fizz' WHEN MOD(level,5)=0 THEN 'Buzz' ELSE TO_CHAR(level) END FizzBuzz FROM dual CONNECT BY LEVEL <= 100;
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#dodo0
dodo0
#Import some functions clojure('count', 1) -> size clojure('nth', 2) -> charAt clojure('inc', 1) -> inc clojure('dec', 1) -> dec clojure('char', 1) -> char clojure('int', 1) -> int clojure('read-line', 0) -> readLine   #The characters we will need charAt("\n", 0) -> newLine charAt("@", 0) -> exitCommand charAt("+", 0) -> incrCommand charAt("-", 0) -> decrCommand charAt("<", 0) -> shlCommand charAt(">", 0) -> shrCommand charAt(".", 0) -> printCommand charAt(",", 0) -> inputCommand charAt("[", 0) -> repeatCommand charAt("]", 0) -> endCommand   #Read a character from a line of input. fun readChar -> return ( readLine() -> line size(line) -> length   #Return the ith character and a continuation fun nextFromLine -> i, return ( '='(i, length) -> eol if (eol) -> ( return(newLine, readChar) #end of line ) | charAt(line, i) -> value inc(i) -> i fun next (-> return) nextFromLine(i, return) | next return(value, next) ) | nextFromLine   nextFromLine(0, return) #first character (position 0) ) | readChar   #Define a buffer as a value and a left and right stack fun empty (-> return, throw) throw("Error: out of bounds") | empty fun fill (-> return, throw) return(0, fill) | fill   fun makeBuffer -> value, left, right, return ( fun buffer (-> return) return(value, left, right) | buffer return(buffer) ) | makeBuffer   fun push -> value, stack, return ( fun newStack (-> return, throw) return(value, stack) | newStack return(newStack) ) | push   #Brainf*** operations fun noop -> buffer, input, return ( return(buffer, input) ) | noop   fun selectOp -> command, return ( '='(command, incrCommand) -> eq if (eq) -> ( fun increment -> buffer, input, return ( buffer() -> value, left, right inc(value) -> value makeBuffer(value, left, right) -> buffer return(buffer, input) ) | increment return(increment) ) | '='(command, decrCommand) -> eq if (eq) -> ( fun decrement -> buffer, input, return ( buffer() -> value, left, right dec(value) -> value makeBuffer(value, left, right) -> buffer return(buffer, input) ) | decrement return(decrement) ) | '='(command, shlCommand) -> eq if (eq) -> ( fun shiftLeft -> buffer, input, return ( buffer() -> value, left, right push(value, right) -> right left() -> value, left ( makeBuffer(value, left, right) -> buffer return(buffer, input) ) | message println(message) -> exit() ) | shiftLeft return(shiftLeft) ) | '='(command, shrCommand) -> eq if (eq) -> ( fun shiftRight -> buffer, input, return ( buffer() -> value, left, right push(value, left) -> left right() -> value, right ( makeBuffer(value, left, right) -> buffer return(buffer, input) ) | message println(message) -> exit() ) | shiftRight return(shiftRight) ) | '='(command, printCommand) -> eq if (eq) -> ( fun putChar -> buffer, input, return ( buffer() -> value, left, right char(value) -> value 'print'(value) -> dummy 'flush'() -> dummy return(buffer, input) ) | putChar return(putChar) ) | '='(command, inputCommand) -> eq if (eq) -> ( fun getChar -> buffer, input, return ( input() -> letter, input int(letter) -> letter buffer() -> value, left, right makeBuffer(letter, left, right) -> buffer return(buffer, input) ) | getChar return(getChar) ) | return(noop) ) | selectOp   #Repeat until zero operation fun whileLoop -> buffer, input, continue, break ( buffer() -> value, left, right '='(value, 0) -> zero if (zero) -> ( break(buffer, input) ) | continue(buffer, input) -> buffer, input whileLoop(buffer, input, continue, break) ) | whileLoop   #Convert the Brainf*** program into dodo0 instructions fun compile -> input, endmark, return ( input() -> command, input   '='(command, endmark) -> eq if (eq) -> ( return(noop, input) #the end, stop compiling ) | #Put in sequence the current operation and the rest of the program fun chainOp -> op, input, return ( compile(input, endmark) -> program, input fun exec -> buffer, input, return ( op(buffer, input) -> buffer, input program(buffer, input, return) ) | exec return(exec, input) ) | chainOp   '='(command, repeatCommand) -> eq if (eq) -> ( compile(input, endCommand) -> body, input #compile until "]"   #Repeat the loop body until zero fun repeat -> buffer, input, return ( whileLoop(buffer, input, body, return) ) | repeat chainOp(repeat, input, return) ) | selectOp(command) -> op chainOp(op, input, return) ) | compile   #Main program compile(readChar, exitCommand) -> program, input makeBuffer(0, empty, fill) -> buffer input() -> nl, input #consume newline from input   #Execute the program instructions program(buffer, input) -> buffer, input exit()
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Euphoria
Euphoria
constant table = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " function random_generation(integer len) sequence s s = rand(repeat(length(table),len)) for i = 1 to len do s[i] = table[s[i]] end for return s end function   function mutate(sequence s, integer n) for i = 1 to length(s) do if rand(n) = 1 then s[i] = table[rand(length(table))] end if end for return s end function   function fitness(sequence probe, sequence target) atom sum sum = 0 for i = 1 to length(target) do sum += power(find(target[i], table) - find(probe[i], table), 2) end for return sqrt(sum/length(target)) end function   constant target = "METHINKS IT IS LIKE A WEASEL", C = 30, MUTATE = 15 sequence parent, specimen integer iter, best atom fit, best_fit parent = random_generation(length(target)) iter = 0 while not equal(parent,target) do best_fit = fitness(parent, target) printf(1,"Iteration: %3d, \"%s\", deviation %g\n", {iter, parent, best_fit}) specimen = repeat(parent,C+1) best = C+1 for i = 1 to C do specimen[i] = mutate(specimen[i], MUTATE) fit = fitness(specimen[i], target) if fit < best_fit then best_fit = fit best = i end if end for parent = specimen[best] iter += 1 end while printf(1,"Finally, \"%s\"\n",{parent})
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Lush
Lush
(de fib-rec (n) (if (< n 2) n (+ (fib-rec (- n 2)) (fib-rec (- n 1)))))
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Ursa
Ursa
import "os" for Process   var hq9plus = Fn.new { |code| var acc = 0 var sb = "" for (c in code) { if (c == "h" || c == "H") { sb = sb + "Hello, world!\n" } else if (c == "q" || c == "Q") { sb = sb + code + "\n" } else if (c == "9") { for (i in 99..1) { var s = (i > 1) ? "s" : "" sb = sb + "%(i) bottle%(s) of beer on the wall\n" sb = sb + "%(i) bottle%(s) of beer\n" sb = sb + "Take one down, pass it around\n" } sb = sb + "No more bottles of beer on the wall!\n" } else if (c == "+") { acc = acc + 1 } else { Fiber.abort("Code contains illegal operation '%(c)'") } } System.print(sb) }   var args = Process.arguments if (args.count != 1) { System.print("Please pass in the HQ9+ code to be executed.") } else { hq9plus.call(args[0]) }
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>] There is one rule per line. If there is a   .   (period)   present before the   <replacement>,   then this is a terminating rule in which case the interpreter must halt execution. A ruleset consists of a sequence of rules, with optional comments. Rulesets Use the following tests on entries: Ruleset 1 # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate the output: I bought a bag of apples from my brother. Ruleset 2 A test of the terminating rule # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate: I bought a bag of apples from T shop. Ruleset 3 This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped. # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As W my Bgage from T S. Should generate: I bought a bag of apples with my money from T shop. Ruleset 4 This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.) ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> Sample text of: _1111*11111_ should generate the output: 11111111111111111111 Ruleset 5 A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s,   the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets. # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 This ruleset should turn 000000A000000 into 00011H1111000
#SequenceL
SequenceL
  import <Utilities/Sequence.sl>;   Rule ::= ( pattern : char(1), replacement : char(1), terminal : bool);   ReplaceResult ::= (newString : char(1), wasReplaced : bool);   main(args(2)) := markov(createRule(split(args[1], '\n')), 1, args[2]);   createRule(line(1)) := let containsComments := firstIndexOf(line, '#'); removedComments := line when containsComments = 0 else line[1 ... containsComments - 1];   arrowLocation := startOfArrow(removedComments, 1); lhs := removedComments[1 ... arrowLocation-1]; rhs := removedComments[arrowLocation + 4 ... size(removedComments)]; isTerminal := size(rhs) > 0 and rhs[1] = '.'; in (pattern : lhs, replacement : rhs[2 ... size(rhs)] when isTerminal else rhs, terminal : isTerminal) when size(removedComments) > 0 and arrowLocation /= -1;   startOfArrow(line(1), n) := -1 when n > size(line) - 3 else n when (line[n]=' ' or line[n]='\t') and line[n+1] = '-' and line[n+2] = '>' and (line[n+3]=' ' or line[n+3]='\t') else startOfArrow(line, n+1);   markov(rules(1), n, input(1)) := let replaced := replaceSubString(input, rules[n].pattern, rules[n].replacement, 1); in input when n > size(rules) else replaced.newString when replaced.wasReplaced and rules[n].terminal else markov(rules, 1, replaced.newString) when replaced.wasReplaced else markov(rules, n+1, input);   replaceSubString(str(1), original(1), new(1), n) := (newString : str, wasReplaced : false) when n > size(str) - size(original) + 1 else (newString : str[1 ... n - 1] ++ new ++ str[n + size(original) ... size(str)], wasReplaced : true) when equalList(str[n ... n + size(original) - 1], original) else replaceSubString(str, original, new, n + 1);    
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>] There is one rule per line. If there is a   .   (period)   present before the   <replacement>,   then this is a terminating rule in which case the interpreter must halt execution. A ruleset consists of a sequence of rules, with optional comments. Rulesets Use the following tests on entries: Ruleset 1 # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate the output: I bought a bag of apples from my brother. Ruleset 2 A test of the terminating rule # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate: I bought a bag of apples from T shop. Ruleset 3 This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped. # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As W my Bgage from T S. Should generate: I bought a bag of apples with my money from T shop. Ruleset 4 This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.) ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> Sample text of: _1111*11111_ should generate the output: 11111111111111111111 Ruleset 5 A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s,   the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets. # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 This ruleset should turn 000000A000000 into 00011H1111000
#SNOBOL4
SNOBOL4
  #!/bin/sh exec "snobol4" "-r" "$0" "$@" * * http://rosettacode.org/wiki/Execute_a_Markov_algorithm * define('repl(s1,s2,s3)c,t,findc') :(repl_end) repl s2 len(1) . c = :f(freturn) findc = break(c) . t len(1) s2 = pos(0) s2 repl_1 s1 findc = :f(repl_2) s1 s2 = :f(repl_3) repl = repl t s3 :(repl_1) repl_3 repl = repl t c :(repl_1) repl_2 repl = repl s1 :(return) repl_end * define('quote(s)q,qq') :(quote_end) quote q = "'"; qq = '"' quote = q repl(s, q, q ' ' qq q qq ' ' q) q :(return) quote_end * whitespace = span(' ' char(9)) top r = 0 read s = input :f(end) s pos(0) 'ENDRULE' rpos(0) :s(interp) s pos(0) '#' :s(read) pattern =; replacement =; term = s arb . pattern whitespace '->' whitespace + ('.' | '') . term arb . replacement rpos(0) :f(syntax) r = r + 1 f = ident(term, '.') ' :(done)' f = ident(term) ' :f(rule' r + 1 ')s(rule1)' c = 'rule' r ' s ' quote(pattern) ' = ' quote(replacement) f code(c) :s(read) output = 'rule: ' s ' generates code ' c ' in error' :(end) syntax output = 'rule: ' s ' in error' :(read) interp code('rule' r + 1 ' :(done)') go s = input :f(end) s pos(0) 'END' rpos(0) :s(top)f(rule1) done output = s :(go) end # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule ENDRULE I bought a B of As from T S. END # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule ENDRULE I bought a B of As from T S. END # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule ENDRULE I bought a B of As W my Bgage from T S. END ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> ENDRULE _1111*11111_ END # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 ENDRULE 000000A000000 END  
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Phix
Phix
throw("oh no") throw(1) throw(501,{"she",made[me],Do(it)})
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#PHL
PHL
module exceptions;   extern printf;   struct @MyException : @Exception {   };   @Void func throws ex [ throw new @MyException; ]   @Integer main [ try func(); catch (e) { if (e::getType == "MyException") { printf("MyException thrown!\n"); } else { printf("Unhandled exception!\n"); } } return 0; ]
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Logtalk
Logtalk
os::shell('ls -a').
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Lua
Lua
-- just executing the command os.execute("ls")   -- to execute and capture the output, use io.popen local f = io.popen("ls") -- store the output in a "file" print( f:read("*a") ) -- print out the "file"'s content
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#M4
M4
syscmd(ifdef(`__windows__',`dir',`ls'))
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#bc
bc
#! /usr/bin/bc -q   define f(x) { if (x <= 1) return (1); return (f(x-1) * x) } f(1000) quit
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#R
R
# Method pow <- function(x, y) { x <- as.numeric(x) y <- as.integer(y) prod(rep(x, y)) } #Operator "%pow%" <- function(x,y) pow(x,y)   pow(3, 4) # 81 2.5 %pow% 2 # 6.25
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Racket
Racket
#lang racket (define (^ base expt) (for/fold ((acum 1)) ((i (in-range expt))) (* acum base)))   (^ 5 2) ; 25 (^ 5.0 2) ; 25.0
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#SQL
SQL
SELECT CASE WHEN MOD(level,15)=0 THEN 'FizzBuzz' WHEN MOD(level,3)=0 THEN 'Fizz' WHEN MOD(level,5)=0 THEN 'Buzz' ELSE TO_CHAR(level) END FizzBuzz FROM dual CONNECT BY LEVEL <= 100;
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#E
E
USE: brainf***   "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." run-brainf***
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#F.23
F#
  //A functional implementation of Evolutionary algorithm //Nigel Galloway February 7th., 2018 let G=System.Random 23 let fitness n=Array.fold2(fun a n g->if n=g then a else a+1) 0 n ("METHINKS IT IS LIKE A WEASEL".ToCharArray()) let alphabet="QWERTYUIOPASDFGHJKLZXCVBNM ".ToCharArray() let mutate (n:char[]) g=Array.iter(fun g->n.[g]<-alphabet.[G.Next()%27]) (Array.init g (fun _->G.Next()%(Array.length n)));n let nextParent n g=List.init 500 (fun _->mutate (Array.copy n) g)|>List.minBy fitness let evolution n=let rec evolution n g=match fitness n with |0->(0,n)::g |l->evolution (nextParent n ((l/2)+1)) ((l,n)::g) evolution n [] let n = evolution (Array.init 28 (fun _->alphabet.[G.Next()%27]))  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#M2000_Interpreter
M2000 Interpreter
  Inventory K=0:=0,1:=1 fib=Lambda K (x as decimal)-> { If Exist(K, x) Then =Eval(K) :Exit Def Ret as Decimal Ret=If(x>1->Lambda(x-1)+Lambda(x-2), x) Append K, x:=Ret =Ret } \\ maximum 139 For i=1 to 139 { Print Fib(i) }  
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Ursala
Ursala
import "os" for Process   var hq9plus = Fn.new { |code| var acc = 0 var sb = "" for (c in code) { if (c == "h" || c == "H") { sb = sb + "Hello, world!\n" } else if (c == "q" || c == "Q") { sb = sb + code + "\n" } else if (c == "9") { for (i in 99..1) { var s = (i > 1) ? "s" : "" sb = sb + "%(i) bottle%(s) of beer on the wall\n" sb = sb + "%(i) bottle%(s) of beer\n" sb = sb + "Take one down, pass it around\n" } sb = sb + "No more bottles of beer on the wall!\n" } else if (c == "+") { acc = acc + 1 } else { Fiber.abort("Code contains illegal operation '%(c)'") } } System.print(sb) }   var args = Process.arguments if (args.count != 1) { System.print("Please pass in the HQ9+ code to be executed.") } else { hq9plus.call(args[0]) }
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>] There is one rule per line. If there is a   .   (period)   present before the   <replacement>,   then this is a terminating rule in which case the interpreter must halt execution. A ruleset consists of a sequence of rules, with optional comments. Rulesets Use the following tests on entries: Ruleset 1 # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate the output: I bought a bag of apples from my brother. Ruleset 2 A test of the terminating rule # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate: I bought a bag of apples from T shop. Ruleset 3 This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped. # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As W my Bgage from T S. Should generate: I bought a bag of apples with my money from T shop. Ruleset 4 This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.) ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> Sample text of: _1111*11111_ should generate the output: 11111111111111111111 Ruleset 5 A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s,   the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets. # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 This ruleset should turn 000000A000000 into 00011H1111000
#Swift
Swift
import Foundation   func setup(ruleset: String) -> [(String, String, Bool)] { return ruleset.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) .filter { $0.rangeOfString("^s*#", options: .RegularExpressionSearch) == nil } .reduce([(String, String, Bool)]()) { rules, line in let regex = try! NSRegularExpression(pattern: "^(.+)\\s+->\\s+(\\.?)(.*)$", options: .CaseInsensitive) guard let match = regex.firstMatchInString(line, options: .Anchored, range: NSMakeRange(0, line.characters.count)) else { return rules } return rules + [( (line as NSString).substringWithRange(match.rangeAtIndex(1)), (line as NSString).substringWithRange(match.rangeAtIndex(3)), (line as NSString).substringWithRange(match.rangeAtIndex(2)) != "" )] } }   func markov(ruleset: String, var input: String) -> String { let rules = setup(ruleset) var terminate = false while !terminate { guard let i = rules.indexOf ({ if let range = input.rangeOfString($0.0) { input.replaceRange(range, with: $0.1) return true } return false }) else { break } terminate = rules[i].2 } return input }     let tests: [(ruleset: String, input: String)] = [ ("# This rules file is extracted from Wikipedia:\n# http://en.wikipedia.org/wiki/Markov_Algorithm\nA -> apple\nB -> bag\nS -> shop\nT -> the\nthe shop -> my brother\na never used -> .terminating rule", "I bought a B of As from T S."), ("# Slightly modified from the rules on Wikipedia\nA -> apple\nB -> bag\nS -> .shop\nT -> the\nthe shop -> my brother\na never used -> .terminating rule", "I bought a B of As from T S."), ("# BNF Syntax testing rules\nA -> apple\nWWWW -> with\nBgage -> ->.*\nB -> bag\n->.* -> money\nW -> WW\nS -> .shop\nT -> the\nthe shop -> my brother\na never used -> .terminating rule", "I bought a B of As W my Bgage from T S."), ("### Unary Multiplication Engine, for testing Markov Algorithm implementations\n### By Donal Fellows.\n# Unary addition engine\n_+1 -> _1+\n1+1 -> 11+\n# Pass for converting from the splitting of multiplication into ordinary\n# addition\n1! -> !1\n,! -> !+\n_! -> _\n# Unary multiplication by duplicating left side, right side times\n1*1 -> x,@y\n1x -> xX\nX, -> 1,1\nX1 -> 1X\n_x -> _X\n,x -> ,X\ny1 -> 1y\ny_ -> _\n# Next phase of applying\n1@1 -> x,@y\n1@_ -> @_\n,@_ -> !_\n++ -> +\n# Termination cleanup for addition\n_1 -> 1\n1+_ -> 1\n_+_ ->", "_1111*11111_"), ("# Turing machine: three-state busy beaver\n#\n# state A, symbol 0 => write 1, move right, new state B\nA0 -> 1B\n# state A, symbol 1 => write 1, move left, new state C\n0A1 -> C01\n1A1 -> C11\n# state B, symbol 0 => write 1, move left, new state A\n0B0 -> A01\n1B0 -> A11\n# state B, symbol 1 => write 1, move right, new state B\nB1 -> 1B\n# state C, symbol 0 => write 1, move left, new state B\n0C0 -> B01\n1C0 -> B11\n# state C, symbol 1 => write 1, move left, halt\n0C1 -> H01\n1C1 -> H11", "000000A000000") ]   for (index, test) in tests.enumerate() { print("\(index + 1):", markov(test.ruleset, input: test.input)) }    
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#PHP
PHP
class MyException extends Exception { // Custom exception attributes & methods }
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#PicoLisp
PicoLisp
(catch 'thisLabel # Catch this label (println 1) # Do some processing (print '1') (throw 'thisLabel 2) # Abort processing and return '2' (println 3) ) # This is never reached
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Make
Make
contents=$(shell cat foo) curdir=`pwd`
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Maple
Maple
ssystem("dir");
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Beads
Beads
beads 1 program Factorial // only works for cardinal numbers 0..N calc main_init log to_str(Iterative(4)) // 24 log to_str(Recursive(5)) // 120   calc Iterative( n:num -- number of iterations ):num -- result var total = 1 loop from:2 to:n index:ix total = ix * total return total   calc Recursive ditto if n <= 1 return 1 else return n * Recursive(n-1)
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Raku
Raku
subset Natural of Int where { $^n >= 0 }   multi pow (0, 0) { fail '0**0 is undefined' } multi pow ($base, Natural $exp) { [*] $base xx $exp } multi pow ($base, Int $exp) { 1 / pow $base, -$exp }   sub infix:<***> ($a, $b) { pow $a, $b }   # Testing   say pow .75, -5; say .75 *** -5;
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Squirrel
Squirrel
function Fizzbuzz(n) { for (local i = 1; i <= n; i += 1) { if (i % 15 == 0) print ("FizzBuzz\n") else if (i % 5 == 0) print ("Buzz\n") else if (i % 3 == 0) print ("Fizz\n") else { print (i + "\n") } } } Fizzbuzz(100);
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Elena
Elena
USE: brainf***   "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." run-brainf***
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Factor
Factor
USING: arrays formatting io kernel literals math prettyprint random sequences strings ; FROM: math.extras => ... ; IN: rosetta-code.evolutionary-algorithm   CONSTANT: target "METHINKS IT IS LIKE A WEASEL" CONSTANT: mutation-rate 0.1 CONSTANT: num-children 25 CONSTANT: valid-chars $[ CHAR: A ... CHAR: Z >array { 32 } append ]   : rand-char ( -- n ) valid-chars random ;   : new-parent ( -- str ) target length [ rand-char ] replicate >string ;   : fitness ( str -- n ) target [ = ] { } 2map-as sift length ;   : mutate ( str rate -- str/str' ) [ random-unit > [ drop rand-char ] when ] curry map ;   : next-parent ( str -- str/str' ) dup [ mutation-rate mutate ] curry num-children 1 - swap replicate [ 1array ] dip append [ fitness ] supremum-by ;   : print-parent ( str -- ) [ fitness pprint bl ] [ print ] bi ;   : main ( -- ) 0 new-parent [ dup target = ] [ next-parent dup print-parent [ 1 + ] dip ] until drop "Finished in %d generations." printf ;   MAIN: main
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#M4
M4
define(`fibo',`ifelse(0,$1,0,`ifelse(1,$1,1, `eval(fibo(decr($1)) + fibo(decr(decr($1))))')')')dnl define(`loop',`ifelse($1,$2,,`$3($1) loop(incr($1),$2,`$3')')')dnl loop(0,15,`fibo')
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Wren
Wren
import "os" for Process   var hq9plus = Fn.new { |code| var acc = 0 var sb = "" for (c in code) { if (c == "h" || c == "H") { sb = sb + "Hello, world!\n" } else if (c == "q" || c == "Q") { sb = sb + code + "\n" } else if (c == "9") { for (i in 99..1) { var s = (i > 1) ? "s" : "" sb = sb + "%(i) bottle%(s) of beer on the wall\n" sb = sb + "%(i) bottle%(s) of beer\n" sb = sb + "Take one down, pass it around\n" } sb = sb + "No more bottles of beer on the wall!\n" } else if (c == "+") { acc = acc + 1 } else { Fiber.abort("Code contains illegal operation '%(c)'") } } System.print(sb) }   var args = Process.arguments if (args.count != 1) { System.print("Please pass in the HQ9+ code to be executed.") } else { hq9plus.call(args[0]) }
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>] There is one rule per line. If there is a   .   (period)   present before the   <replacement>,   then this is a terminating rule in which case the interpreter must halt execution. A ruleset consists of a sequence of rules, with optional comments. Rulesets Use the following tests on entries: Ruleset 1 # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate the output: I bought a bag of apples from my brother. Ruleset 2 A test of the terminating rule # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate: I bought a bag of apples from T shop. Ruleset 3 This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped. # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As W my Bgage from T S. Should generate: I bought a bag of apples with my money from T shop. Ruleset 4 This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.) ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> Sample text of: _1111*11111_ should generate the output: 11111111111111111111 Ruleset 5 A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s,   the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets. # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 This ruleset should turn 000000A000000 into 00011H1111000
#Tcl
Tcl
package require Tcl 8.5 if {$argc < 3} {error "usage: $argv0 ruleFile inputFile outputFile"} lassign $argv ruleFile inputFile outputFile   # Read the file of rules set rules {} set f [open $ruleFile] foreach line [split [read $f] \n[close $f]] { if {[string match "#*" $line] || $line eq ""} continue if {[regexp {^(.+)\s+->\s+(\.?)(.*)$} $line -> from final to]} { lappend rules $from $to [string compare "." $final] [string length $from] } else { error "Syntax error: \"$line\"" } }   # Apply the rules set f [open $inputFile] set out [open $outputFile w] foreach line [split [read $f] \n[close $f]] { set any 1 while {$any} { set any 0 foreach {from to more fl} $rules { # If we match the 'from' pattern... if {[set idx [string first $from $line]] >= 0} { # Change for the 'to' replacement set line [string replace $line $idx [expr {$idx+$fl-1}] $to]   # Stop if we terminate, otherwise note that we've more work to do set any $more break; # Restart search for rules to apply } } #DEBUG# puts $line }   # Output the processed line puts $out $line } close $out
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#PL.2FI
PL/I
  /* Define a new exception, called "my_condition". */ on condition (my_condition) snap begin; put skip list ('My condition raised.'); end;   /* Raise that exception */ signal condition (my_condition);   /* Raising that exception causes the message "My condition raised" */ /* to be printed, and execution then resumes at the statement */ /* following the SIGNAL statement. */  
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#PL.2FpgSQL
PL/pgSQL
  BEGIN raise exception 'this is a generic user exception'; raise exception division_by_zero; END;  
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Run["ls"]
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#MATLAB
MATLAB
>> system('PAUSE')   Press any key to continue . . .     ans =   0  
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Maxima
Maxima
system("dir > list.txt")$
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#beeswax
beeswax
p < _>1FT"pF>M"p~.~d >Pd >~{Np d <
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Retro
Retro
: pow ( bp-n ) 1 swap [ over * ] times nip ;
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#REXX
REXX
/*REXX program computes and displays various (integer) exponentiations. */ say center('digits='digits(), 79, "─") say 'iPow(17, 65) is:' say iPow(17, 65) say   say 'iPow(0, -3) is:' say iPow(0, -3) say   say 'iPow(8, 0) is:' say iPow(8, 0) say   numeric digits 12; say center('digits='digits(), 79, "─") say 'iPow(2, -10) is:' say iPow(2, -10) say   numeric digits 30; say center('digits='digits(), 79, "─") say 'iPow(-3.1415926535897932384626433, 3) is:' say iPow(-3.1415926535897932384626433, 3) say   numeric digits 60; say center('digits='digits(), 79, "─") say 'iPow(5, 70) is:' say iPow(5, 70) say   numeric digits 100; say center('digits='digits(), 79, "─") say 'iPow(17, 65) is:' say iPow(17, 65) say   numeric digits 1000; say center('digits='digits(), 79, "─") say 'iPow(2, 1000) is:' say iPow(2, 1000) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ errMsg: say; say '***error***'; say; say arg(1); say; say; exit 13 /*──────────────────────────────────────────────────────────────────────────────────────*/ iPow: procedure; parse arg x 1 _,p; #args= arg() /*_: is a copy of X. */ if #args<2 then call errMsg "not enough arguments specified" if #args>2 then call errMsg "too many arguments specified" if \datatype(x, 'N') then call errMsg "1st arg isn't numeric:" x if \datatype(p, 'W') then call errMsg "2nd arg isn't an integer:" p if p=0 then return 1 /*handle powers of zero. */ if x=0 | x=1 then return x /*handle special cases. */ do abs(p) - 1; _= _ * x; end /*perform exponentiation */ if p<0 then _= 1 / _ /*process its reciprocal.*/ return _
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Stata
Stata
program define fizzbuzz args n forvalues i = 1/`n' { if mod(`i',15) == 0 { display "FizzBuzz" } else if mod(`i',5) == 0 { display "Buzz" } else if mod(`i',3) == 0 { display "Fizz" } else { display `i' } } end
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Erlang
Erlang
USE: brainf***   "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." run-brainf***
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Fantom
Fantom
  class Main { static const Str target := "METHINKS IT IS LIKE A WEASEL" static const Int C := 100 // size of population static const Float p := 0.1f // chance any char is mutated   // compute distance of str from target static Int fitness (Str str) { Int sum := 0 str.each |Int c, Int index| { if (c != target[index]) sum += 1 } return sum }   // mutate given parent string static Str mutate (Str str) { Str result := "" str.size.times |Int index| { result += ((Float.random < p) ? randomChar() : str[index]).toChar } return result }   // return a random char static Int randomChar () { "ABCDEFGHIJKLMNOPQRSTUVWXYZ "[Int.random(0..26)] }   // make population by mutating parent and sorting by fitness static Str[] makePopulation (Str parent) { Str[] result := [,] C.times { result.add (mutate(parent)) } result.sort |Str a, Str b -> Int| { fitness(a) <=> fitness(b) } return result }   public static Void main () { Str parent := "" target.size.times { parent += randomChar().toChar }   while (parent != target) { echo (parent) parent = makePopulation(parent).first } echo (parent) } }  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(N) ENTRY TO FIB. A = 0 B = 1 THROUGH LOOP, FOR N=N, -1, N.E.0 C = A + B A = B LOOP B = C FUNCTION RETURN A END OF FUNCTION   THROUGH SHOW, FOR I=0, 1, I.GE.20 SHOW PRINT FORMAT FNUM, I, FIB.(I) VECTOR VALUES FNUM = $4HFIB(,I2,4H) = ,I4*$ END OF PROGRAM
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#x86_Assembly
x86 Assembly
    ;ds:si: pointer to asciiz string containing HQ9++ source code ExecuteHQ9: push ax push dx push si push di push es push bx mov bx, si .interpret: lodsb cmp al, 'H' je .doHelloWorld cmp al, 'Q' je .doPrintCode cmp al, '9' je .doDrinkBeer cmp al, '+' je .doCounter pop bx pop es pop di pop si pop dx pop ax ret   .doHelloWorld: push ds mov ax, cs mov ds, ax push si mov si, .dataHelloWorld call .printString pop si pop ds jmp .interpret   .doPrintCode: push si mov si, bx call .printString pop si jmp .interpret   .doDrinkBeer: push ds push si push ax mov ax, cs mov ds, ax mov ax, 99 .beer_loop: call .printHexNumber mov si, .dataBeerSong1 call .printString call .printHexNumber mov si, .dataBeerSong2 call .printString dec ax call .printHexNumber mov si, .dataBeerSong3 call .printString test ax, ax jnz .beer_loop pop ax pop si pop ds jmp .interpret   .doCounter: push ax inc ax pop ax jmp .interpret   .printString: push ax push si .looping: lodsb test al, al jz .done mov ah, 0Eh int 10h jmp .looping .done: pop si pop ax ret   .printHexNumber: pusha push ds mov ax, cs mov ds, ax push word 0 mov bx, ax xor dx, dx mov cx, 4r .convert_loop: mov ax, bx and ax, 0Fh cmp ax, 9 ja .greater_than_9 add ax, '0' jmp .converted .greater_than_9: add ax, 'A'-0Ah .converted: push ax shr bx, 4 dec cx jnz .convert_loop .popoff: pop ax cmp ax, 0 je .done mov ah, 0Eh int 10h jmp .popoff .done: pop ds popa ret   .dataHelloWorld: db "Hello World!", 0 .dataBeerSong1: db " bottles of beer on the wall ", 0 .dataBeerSong2: db " bottles of beer", 13, 10, "Take one down, pass it around " .dataBeerSong3: db 0, " bottles of beer on the wall", 0    
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#XSLT
XSLT
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <!-- bottles.xsl defines $entire-bottles-song --> <xsl:import href="bottles.xsl"/>   <xsl:output method="text" encoding="utf-8"/>   <xsl:variable name="hello-world"> <xsl:text>Hello, world!&#10;</xsl:text> </xsl:variable>   <!-- Main template --> <xsl:template match="/"> <xsl:call-template name="run"> <xsl:with-param name="code" select="string(.)"/> </xsl:call-template> </xsl:template>   <!-- Runs HQ9+ code from string starting at given index (default 1) --> <xsl:template name="run"> <xsl:param name="code"/> <xsl:param name="starting-at" select="1"/>   <!-- Fetches instruction and forces to upper-case --> <xsl:variable name="inst" select="translate(substring($code, $starting-at, 1), 'hq', 'HQ')"/>   <!-- Only if not at end --> <xsl:if test="$inst != ''"> <xsl:choose> <xsl:when test="$inst = 'H'"> <xsl:value-of select="$hello-world"/> </xsl:when> <xsl:when test="$inst = 'Q'"> <xsl:value-of select="$code"/> <xsl:text>&#10;</xsl:text> </xsl:when> <xsl:when test="$inst = '9'"> <xsl:value-of select="$entire-bottles-song"/> </xsl:when> <xsl:when test="$inst = '+'"> <!-- XSLT has no meaningful equivalent of write-only variables --> </xsl:when> <!-- Otherwise, do nothing --> </xsl:choose>   <!-- Proceed with next instruction --> <xsl:call-template name="run"> <xsl:with-param name="code" select="$code"/> <xsl:with-param name="starting-at" select="$starting-at + 1"/> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet>
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>] There is one rule per line. If there is a   .   (period)   present before the   <replacement>,   then this is a terminating rule in which case the interpreter must halt execution. A ruleset consists of a sequence of rules, with optional comments. Rulesets Use the following tests on entries: Ruleset 1 # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate the output: I bought a bag of apples from my brother. Ruleset 2 A test of the terminating rule # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate: I bought a bag of apples from T shop. Ruleset 3 This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped. # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As W my Bgage from T S. Should generate: I bought a bag of apples with my money from T shop. Ruleset 4 This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.) ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> Sample text of: _1111*11111_ should generate the output: 11111111111111111111 Ruleset 5 A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s,   the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets. # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 This ruleset should turn 000000A000000 into 00011H1111000
#VBScript
VBScript
  class markovparser   dim aRules public property let ruleset( sBlock ) dim i aRules = split( sBlock, vbNewLine ) '~ remove blank lines from end of array do while aRules( ubound( aRules ) ) = vbnullstring redim preserve aRules( ubound( aRules ) - 1 ) loop '~ parse array for i = lbound( aRules ) to ubound( aRules ) if left( aRules( i ), 1 ) = "#" then aRules( i ) = Array( vbnullstring, aRules(i)) else aRules( i ) = Split( aRules( i ), " -> ", 2 ) end if next end property   public function apply( sArg ) dim ruleapplied dim terminator dim was dim i dim repl dim changes   ruleapplied = true terminator = false   do while ruleapplied and (not terminator) changes = 0 was = sArg for i = lbound( aRules ) to ubound( aRules ) repl = aRules(i)(1) if left( repl, 1 ) = "." then terminator = true repl = mid( repl, 2 ) end if sArg = replace( sArg, aRules(i)(0), repl) if was <> sArg then changes = changes + 1 if changes = 1 then exit for end if end if if terminator then exit for end if next if changes = 0 then ruleapplied = false end if loop apply = sArg end function   sub dump dim i for i = lbound( aRules ) to ubound( aRules ) wscript.echo eef(aRules(i)(0)=vbnullstring,aRules(i)(1),aRules(i)(0)& " -> " & aRules(i)(1)) & eef( left( aRules(i)(1), 1 ) = ".", " #terminator", "" ) next end sub   private function eef( bCond, sExp1, sExp2 ) if bCond then eef = sExp1 else eef = sExp2 end if end function end class  
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Pop11
Pop11
define throw_exception(); throw([my_exception my_data]); enddefine;
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#PowerShell
PowerShell
  throw "Any error message."  
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#MAXScript
MAXScript
dosCommand "pause"
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Mercury
Mercury
  :- module execute_sys_cmd. :- interface. :- import_module io.   :- pred main(io::di, io::uo) is det.   :- implementation.   main(!IO) :- io.call_system("ls", _Result, !IO).  
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#min
min
!dir
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Befunge
Befunge
&1\>  :v v *< ^-1:_$>\:| @.$<
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Ring
Ring
  see "11^5 = " + ipow(11, 5) + nl see "pi^3 = " + fpow(3.14, 3) + nl   func ipow a, b p2 = 1 for i = 1 to 32 p2 *= p2 if b < 0 p2 *= a ok b = b << 1 next return p2   func fpow a, b p = 1 for i = 1 to 32 p *= p if b < 0 p *= a ok b = b << 1 next return p  
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Ruby
Ruby
class Numeric def pow(m) raise TypeError, "exponent must be an integer: #{m}" unless m.is_a? Integer puts "pow!!" Array.new(m, self).reduce(1, :*) end end   p 5.pow(3) p 5.5.pow(3) p 5.pow(3.1)
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Swahili
Swahili
  shughuli fizzBuzz() { kwa i = 1 mpaka 100 { kama (i % 15 == 0) { andika("FizzBuzz") } au (i % 5 == 0) { andika("Buzz") } au (i % 3 == 0) { andika("Fizz") } sivyo { andika(i) } } }  
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#F.23
F#
USE: brainf***   "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." run-brainf***
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Forth
Forth
include lib/choose.4th \ target string s" METHINKS IT IS LIKE A WEASEL" sconstant target   27 constant /charset \ size of characterset 29 constant /target \ size of target string 32 constant #copies \ number of offspring   /target string charset \ characterset /target string this-generation \ current generation and offspring /target #copies [*] string new-generation   :this new-generation does> swap /target chars * + ; \ generate a mutation : mutation charset /charset choose chars + c@ ; \ print the current candidate : .candidate ( n1 n2 -- n1 f) ." Generation " over 2 .r ." : " this-generation count type cr /target -1 [+] = ; \ test a candidate on \ THE NUMBER of correct genes : test-candidate ( a -- a n) dup target 0 >r >r ( a1 a2) begin ( a1 a2) r@ ( a1 a2 n) while ( a1 a2) over c@ over c@ = ( a1 a2 n) r> r> rot if 1+ then >r 1- >r ( a1 a2) char+ swap char+ swap ( a1+1 a2+1) repeat ( a1+1 a2+1) drop drop r> drop r> ( a n) ; \ find the best candidate : get-candidate ( -- n) #copies 0 >r >r ( --) begin ( --) r@ ( n) while ( --) r@ 1- new-generation ( a) test-candidate r'@ over < ( a n f) if swap count this-generation place r> 1- swap r> drop >r >r else drop drop r> 1- >r then ( --) repeat ( --) r> drop r> ( n) ; \ generate a new candidate : make-candidate ( a --) dup charset count rot place ( a1) this-generation target >r ( a1 a2 a3) begin ( a1 a2 a3) r@ ( a1 a2 a3 n) while ( a1 a2 a3) over c@ over c@ = ( a1 a2 a3 f) swap >r >r over r> ( a1 a2 a1 f) if over c@ else mutation then ( a1 a2 a1 c) swap c! r> r> 1- >r ( a1 a2 a3) char+ rot char+ rot char+ rot ( a1+1 a2+1 a3+1) repeat ( a1+1 a2+1 a3+1) drop drop drop r> drop ( --) ; \ make a whole new generation : make-generation #copies 0 do i new-generation make-candidate loop ; \ weasel program : weasel s" ABCDEFGHIJKLMNOPQRSTUVWXYZ " 2dup charset place \ initialize the characterset this-generation place 0 \ initialize the first generation begin \ start the program 1+ make-generation \ make a new generation get-candidate .candidate \ select the best candidate until drop \ stop when we've found perfection ;   weasel
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Maple
Maple
  > f := n -> ifelse(n<3,1,f(n-1)+f(n-2)); > f(2); 1 > f(3); 2  
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#zkl
zkl
fcn runHQ9(code){ acc:=0; foreach c in (code){ switch(c){ case("H"){ println("hello, world"); } case("Q"){ print(code); } case("+"){ acc+=1; } case("9"){ wall_O_beer(); } } } } fcn wall_O_beer(){ [99..0,-1].pump(fcn(n){ println(beers(n), " on the wall, ", beers(n).toLower(), ".\n", n==0 and ("Go to the store and buy some more, 99 bottles of beer") or ("Take one down and pass it around, " + beers(n-1).toLower()), " on the wall.\n") }); } fcn beers(n){ (n==0 and "No more bottles" or (n==1 and "1 bottle" or "" + n + " bottles")) + " of beer" }
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>] There is one rule per line. If there is a   .   (period)   present before the   <replacement>,   then this is a terminating rule in which case the interpreter must halt execution. A ruleset consists of a sequence of rules, with optional comments. Rulesets Use the following tests on entries: Ruleset 1 # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate the output: I bought a bag of apples from my brother. Ruleset 2 A test of the terminating rule # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate: I bought a bag of apples from T shop. Ruleset 3 This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped. # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As W my Bgage from T S. Should generate: I bought a bag of apples with my money from T shop. Ruleset 4 This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.) ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> Sample text of: _1111*11111_ should generate the output: 11111111111111111111 Ruleset 5 A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s,   the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets. # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 This ruleset should turn 000000A000000 into 00011H1111000
#Wren
Wren
import "/ioutil" for FileUtil, File import "/pattern" for Pattern   var lb = FileUtil.lineBreak   /* rulesets assumed to be separated by a blank line in file */ var readRules = Fn.new { |path| return File.read(path).trimEnd().split("%(lb)%(lb)").map { |rs| rs.split(lb) }.toList }   /* tests assumed to be on consecutive lines */ var readTests = Fn.new { |path| File.read(path).trimEnd().split(lb) }   var rules = readRules.call("markov_rules.txt") var tests = readTests.call("markov_tests.txt") var pattern = Pattern.new("+0/s[~.][+0/z]", Pattern.start) var ix = 0 for (origTest in tests) { var captures = [] for (rule in rules[ix]) { if (rule.startsWith("#")) continue var splits = rule.split(" -> ") var m = pattern.find(splits[1]) if (m) captures.add([splits[0].trimEnd()] + m.capsText) } var test = origTest while (true) { var copy = test var redo = false for (c in captures) { test = test.replace(c[0], c[2]) if (c[1] == ".") break if (test != copy) { redo = true break } } if (!redo) break } System.print("%(origTest)\n%(test)\n") ix = ix + 1 }
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Prolog
Prolog
foo(X) :- \+ integer(X), throw(b('not even an int')). foo(X) :- \+ between(1,10,X), throw(a('must be between 1 & 10')). foo(X) :- format('~p is a valid number~n', X).   go(X) :- catch( foo(X), E, handle(E)).   handle(a(Msg)) :- format('~w~n', Msg), !. handle(X) :- throw(X).
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#PureBasic
PureBasic
Procedure ErrorHandler() MessageRequester("Exception test", "The following error happened: " + ErrorMessage()) EndProcedure   MessageRequester("Exception test", "Test start")   OnErrorCall(@ErrorHandler())   RaiseError(#PB_OnError_InvalidMemory) ;a custom error# can also be used here depending on the OS being compiled for
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Modula-2
Modula-2
MODULE tri;   FROM SYSTEM IMPORT ADR; FROM SysLib IMPORT system;   IMPORT TextIO, InOut, ASCII;   VAR fd : TextIO.File; ch : CHAR;   PROCEDURE SystemCommand (VAR command : ARRAY OF CHAR) : BOOLEAN;   BEGIN IF system (ADR (command) ) = 0 THEN RETURN TRUE ELSE RETURN FALSE END END SystemCommand;   BEGIN IF SystemCommand ("ls -1 tri.mod | ") = TRUE THEN InOut.WriteString ("No error reported.") ELSE InOut.WriteString ("Error reported!") END; LOOP InOut.Read (ch); InOut.Write (ch); IF ch < ' ' THEN EXIT END END; InOut.WriteLn; InOut.WriteBf END tri.
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Modula-3
Modula-3
UNSAFE MODULE Exec EXPORTS Main;   IMPORT Unix, M3toC;   VAR command := M3toC.CopyTtoS("ls");   BEGIN EVAL Unix.system(command); M3toC.FreeCopiedS(command); END Exec.
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#BQN
BQN
Fac ← ×´1+↕ ! 720 ≡ Fac 6
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Run_BASIC
Run BASIC
print " 11^5 = ";11^5 print " (-11)^5 = ";-11^5 print " 11^( -5) = ";11^-5 print " 3.1416^3 = ";3.1416^3 print " 0^2 = ";0^2 print " 2^0 = ";2^0 print " -2^0 = ";-2^0
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Rust
Rust
extern crate num; use num::traits::One; use std::ops::Mul;   fn pow<T>(mut base: T, mut exp: usize) -> T where T: Clone + One + Mul<T, Output=T> { if exp == 0 { return T::one() } while exp & 1 == 0 { base = base.clone() * base; exp >>= 1; } if exp == 1 { return base } let mut acc = base.clone();   while exp > 1 { exp >>= 1; base = base.clone() * base; if exp & 1 == 1 { acc = acc * base.clone(); } } acc }
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Swift
Swift
for i in 1...100 { switch (i % 3, i % 5) { case (0, 0): print("FizzBuzz") case (0, _): print("Fizz") case (_, 0): print("Buzz") default: print(i) } }
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Factor
Factor
USE: brainf***   "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." run-brainf***
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Fortran
Fortran
  !*************************************************************************************************** module evolve_routines !*************************************************************************************************** implicit none   !the target string: character(len=*),parameter :: targ = 'METHINKS IT IS LIKE A WEASEL'   contains !***************************************************************************************************   !******************************************************************** pure elemental function fitness(member) result(n) !******************************************************************** ! The fitness function. The lower the value, the better the match. ! It is zero if they are identical. !********************************************************************   implicit none integer :: n character(len=*),intent(in) :: member   integer :: i   n=0 do i=1,len(targ) n = n + abs( ichar(targ(i:i)) - ichar(member(i:i)) ) end do   !******************************************************************** end function fitness !********************************************************************   !******************************************************************** pure elemental subroutine mutate(member,factor) !******************************************************************** ! mutate a member of the population. !********************************************************************   implicit none character(len=*),intent(inout) :: member !population member real,intent(in) :: factor !mutation factor   integer,parameter :: n_chars = 27 !number of characters in set character(len=n_chars),parameter :: chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '   real :: rnd_val integer :: i,j,n   n = len(member)   do i=1,n rnd_val = rand() if (rnd_val<=factor) then !mutate this element rnd_val = rand() j = int(rnd_val*n_chars)+1 !an integer between 1 and n_chars member(i:i) = chars(j:j) end if end do   !******************************************************************** end subroutine mutate !********************************************************************   !*************************************************************************************************** end module evolve_routines !***************************************************************************************************   !*************************************************************************************************** program evolve !*************************************************************************************************** ! The main program !*************************************************************************************************** use evolve_routines   implicit none   !Tuning parameters: integer,parameter :: seed = 12345 !random number generator seed integer,parameter :: max_iter = 10000 !maximum number of iterations integer,parameter :: population_size = 200 !size of the population real,parameter :: factor = 0.04 ![0,1] mutation factor integer,parameter :: iprint = 5 !print every iprint iterations   !local variables: integer :: i,iter integer,dimension(1) :: i_best character(len=len(targ)),dimension(population_size) :: population   !initialize random number generator: call srand(seed)   !create initial population: ! [the first element of the population will hold the best member] population(1) = 'PACQXJB CQPWEYKSVDCIOUPKUOJY' !initial guess iter=0   write(*,'(A10,A30,A10)') 'iter','best','fitness' write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1))   do   iter = iter + 1 !iteration counter   !write the iteration: if (mod(iter,iprint)==0) write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1))   !check exit conditions: if ( iter>max_iter .or. fitness(population(1))==0 ) exit   !copy best member and mutate: population = population(1) do i=2,population_size call mutate(population(i),factor) end do   !select the new best population member: ! [the best has the lowest value] i_best = minloc(fitness(population)) population(1) = population(i_best(1))   end do   !write the last iteration: if (mod(iter,iprint)/=0) write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1))   if (iter>max_iter) then write(*,*) 'No solution found.' else write(*,*) 'Solution found.' end if   !*************************************************************************************************** end program evolve !***************************************************************************************************  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
fib[0] = 0 fib[1] = 1 fib[n_Integer] := fib[n - 1] + fib[n - 2]
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>] There is one rule per line. If there is a   .   (period)   present before the   <replacement>,   then this is a terminating rule in which case the interpreter must halt execution. A ruleset consists of a sequence of rules, with optional comments. Rulesets Use the following tests on entries: Ruleset 1 # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate the output: I bought a bag of apples from my brother. Ruleset 2 A test of the terminating rule # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate: I bought a bag of apples from T shop. Ruleset 3 This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped. # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As W my Bgage from T S. Should generate: I bought a bag of apples with my money from T shop. Ruleset 4 This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.) ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> Sample text of: _1111*11111_ should generate the output: 11111111111111111111 Ruleset 5 A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s,   the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets. # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 This ruleset should turn 000000A000000 into 00011H1111000
#zkl
zkl
fcn parseRuleSet(lines){ if(vm.numArgs>1) lines=vm.arglist; // lines or object ks:=L(); vs:=L(); foreach line in (lines){ if(line[0]=="#") continue; // nuke <comment> pattern,replacement:=line.replace("\t"," ") .split(" -> ",1).apply("strip"); ks.append(pattern); vs.append(replacement); } return(ks,vs); }   fcn markov(text,rules){ ks,vs:=rules; eks:=ks.enumerate(); do{ go:=False; foreach n,k in (eks){ if (Void!=text.find(k)){ if (Void==(v:=vs[n])) return(text); if (v[0,1]==".") v=v[1,*] else go=True; text=text.replace(k,v,1); break; // restart after every rule application, unless terminating } } }while(go); text }
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Python
Python
import exceptions class SillyError(exceptions.Exception): def __init__(self,args=None): self.args=args
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Quackery
Quackery
<flag on stack indicating if condition detected> if [ $ "It all went pear shaped in 'a'." message put bail ]
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#MUMPS
MUMPS
Set X=$ZF(-1,"DIR")
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Nanoquery
Nanoquery
shell("ls")
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import java.util.Scanner   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static parse arg command if command = '' then command = 'ls -oa' -- for Windows change to: 'cmd /C dir' do say 'Executing command:' command jprocess = Runtime.getRunTime().exec(command) jscanner = Scanner(jprocess.getInputStream()) loop label scanning while jscanner.hasNext() say jscanner.nextLine() end scanning catch ex = IOException ex.printStackTrace() end return  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Bracmat
Bracmat
( = .  !arg:0&1 |  !arg * ( ( = r .  !arg:?r & ' ( .  !arg:0&1 | !arg*(($r)$($r))$(!arg+-1) ) ) $ ( = r .  !arg:?r & ' ( .  !arg:0&1 | !arg*(($r)$($r))$(!arg+-1) ) ) ) $ (!arg+-1) ) $ 10  : 3628800  
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Scala
Scala
object Exponentiation { import scala.annotation.tailrec   @tailrec def powI[N](n: N, exponent: Int)(implicit num: Integral[N]): N = { import num._ exponent match { case 0 => one case _ if exponent % 2 == 0 => powI((n * n), (exponent / 2)) case _ => powI(n, (exponent - 1)) * n } }   @tailrec def powF[N](n: N, exponent: Int)(implicit num: Fractional[N]): N = { import num._ exponent match { case 0 => one case _ if exponent < 0 => one / powF(n, exponent.abs) case _ if exponent % 2 == 0 => powF((n * n), (exponent / 2)) case _ => powF(n, (exponent - 1)) * n } }   class ExponentI[N : Integral](n: N) { def \u2191(exponent: Int): N = powI(n, exponent) }   class ExponentF[N : Fractional](n: N) { def \u2191(exponent: Int): N = powF(n, exponent) }   object ExponentI { implicit def toExponentI[N : Integral](n: N): ExponentI[N] = new ExponentI(n) }   object ExponentF { implicit def toExponentF[N : Fractional](n: N): ExponentF[N] = new ExponentF(n) }   object Exponents { implicit def toExponent(n: Int): ExponentI[Int] = new ExponentI(n) implicit def toExponent(n: Double): ExponentF[Double] = new ExponentF(n) } }