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/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
#Julia
Julia
function extendedsqrt(x) try sqrt(x) catch if x isa Number sqrt(complex(x, 0)) else throw(DomainError()) end end end   @show extendedsqrt(1) # 1 @show extendedsqrt(-1) # 0.0 + 1.0im @show extendedsqrt('x') # ERROR: DomainError
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
#Kotlin
Kotlin
// version 1.0.6   // In Kotlin all Exception classes derive from Throwable and, by convention, end with the word 'Exception' class MyException (override val message: String?): Throwable(message)   fun foo() { throw MyException("Bad foo!") }   fun goo() { try { foo() } catch (me: MyException) { println("Caught MyException due to '${me.message}'") println("\nThe stack trace is:\n") me.printStackTrace() } }   fun main(args: Array<String>) { goo() }
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Shell "dir" Sleep
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
#Frink
Frink
r = callJava["java.lang.Runtime", "getRuntime"] println[read[r.exec["dir"].getInputStream[]]]
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
#FunL
FunL
import sys.execute   execute( if $os.startsWith('Windows') then 'dir' else '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
#ATS
ATS
  fun fact ( n: int ) : int = res where { var n: int = n var res: int = 1 val () = while (n > 0) (res := res * n; n := 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
#Modula-2
Modula-2
  (* Library Interface *) DEFINITION MODULE Exponentiation;   PROCEDURE IntExp(base, exp : INTEGER) : INTEGER; (* Raises base to the power of exp and returns the result both base and exp must be of type INTEGER *)   PROCEDURE RealExp(base : REAL; exp : INTEGER) : REAL; (* Raises base to the power of exp and returns the result base must be of type REAL, exp of type INTEGER *)   END Exponentiation.   (* Library Implementation *) IMPLEMENTATION MODULE Exponentiation;   PROCEDURE IntExp(base, exp : INTEGER) : INTEGER; VAR i, res : INTEGER; BEGIN res := 1; FOR i := 1 TO exp DO res := res * base; END; RETURN res; END IntExp;   PROCEDURE RealExp(base: REAL; exp: INTEGER) : REAL; VAR i : INTEGER; res : REAL; BEGIN res := 1.0; IF exp < 0 THEN FOR i := exp TO -1 DO res := res / base; END; ELSE (* exp >= 0 *) FOR i := 1 TO exp DO res := res * base; END; END; RETURN res; END RealExp;   END Exponentiation.  
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Scala
Scala
scala> def if2[A](x: => Boolean)(y: => Boolean)(xyt: => A) = new { | def else1(xt: => A) = new { | def else2(yt: => A) = new { | def orElse(nt: => A) = { | if(x) { | if(y) xyt else xt | } else if(y) { | yt | } else { | nt | } | } | } | } | } if2: [A](x: => Boolean)(y: => Boolean)(xyt: => A)java.lang.Object{def else1(xt: => A): java.lang.Object{def else2(yt: => A): java.lang.Object{def orElse(nt: => A): A}}}
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
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: number is 0; begin for number range 1 to 100 do if number rem 15 = 0 then writeln("FizzBuzz"); elsif number rem 5 = 0 then writeln("Buzz"); elsif number rem 3 = 0 then writeln("Fizz"); else writeln(number); end if; end for; end func;
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. The routine should be used to: Show the first twenty primes. Show the primes between 100 and 150. Show the number of primes between 7,700 and 8,000. Show the 10,000th prime. Show output on this page. Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). Note 3:The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency). Reference Prime Numbers. Website with large count of primes.
#Ring
Ring
  see "first twenty primes : " i = 1 nr = 0 while i <= 20 nr += 1 if isPrime(nr) see " " + nr i += 1 ok end   see "primes between 100 and 150 : " for nr = 100 to 150 if isPrime(nr) see " " + nr ok next see nl   see "primes between 7,700 and 8,000 : " i = 0 for nr = 7700 to 8000 if isPrime(nr) i += 1 ok next see i + nl   see "The 10,000th prime : " i = 1 nr = 0 while i <= 10000 nr += 1 if isPrime(nr) i += 1 ok end see nr + nl   func isPrime n if n <= 1 return false ok if n <= 3 return true ok if (n & 1) = 0 return false ok for t = 3 to sqrt(n) step 2 if (n % t) = 0 return false ok next return true  
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.
#Brat
Brat
  ".""X"r~"-""\/^^{vvvv}c!!!-.256.%{vvvv}c!sa\/"r~"+""\/^^{vvvv}c!!!+. 256.%{vvvv}c!sa\/"r~"[""{"r~"]""}{\/^^{vvvv}c!!!}w!"r~">""+."r~"<"" -."r~"X""\/^^{vvvv}c!!!L[+]\/+]\/+]^^3\/.+1RAp^\/+]\/[-1RA^^-]\/[-\/ "r~"\'\'1 128r@{vv0}m[0"\/.+pse!vvvv<-sh  
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.
#CLU
CLU
fitness = proc (s, t: string) returns (int) f: int := 0 for i: int in int$from_to(1,string$size(s)) do if s[i] ~= t[i] then f := f-1 end end return(f) end fitness   mutate = proc (mut: int, s: string) returns (string) own charset: string := " ABCDEFGHIJKLMNOPQRSTUVWXYZ" out: array[char] := array[char]$predict(1,string$size(s)) for c: char in string$chars(s) do if random$next(10000) < mut then c := charset[1+random$next(string$size(charset))] end array[char]$addh(out,c) end return(string$ac2s(out)) end mutate   weasel = iter (mut, c: int, tgt: string) yields (string) own charset: string := " ABCDEFGHIJKLMNOPQRSTUVWXYZ" start: array[char] := array[char]$[] for i: int in int$from_to(1,string$size(tgt)) do array[char]$addh(start,charset[1+random$next(string$size(charset))]) end cur: string := string$ac2s(start) while true do yield(cur) if cur = tgt then break end best: string := cur best_fitness: int := fitness(cur, tgt) for i: int in int$from_to(2,c) do next: string := mutate(mut, cur) next_fitness: int := fitness(next, tgt) if best_fitness <= next_fitness then best, best_fitness := next, next_fitness end end cur := best end end weasel   start_up = proc () d: date := now() random$seed(d.second + 60*(d.minute + 60*d.hour)) po: stream := stream$primary_output() for m: string in weasel(100, 1000, "METHINKS IT IS LIKE A WEASEL") do stream$putl(po, m) end end start_up
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
#Lean
Lean
  -- Our first implementation is the usual recursive definition: def fib1 : ℕ → ℕ | 0  := 0 | 1  := 1 | (n + 2) := fib1 n + fib1 (n + 1)     -- We can give a second more efficient implementation using an auxiliary function: def fib_aux : ℕ → ℕ → ℕ → ℕ | 0 a b  := b | (n + 1) a b := fib_aux n (a + b) a   def fib2 : ℕ → ℕ | n := fib_aux n 1 0     -- Use #eval to check computations: #eval fib1 20 #eval fib2 20
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Perl
Perl
#!/usr/bin/perl use warnings; use strict; use feature qw(say switch);   my @programme = <> or die "No input. Specify a program file or pipe it to the standard input.\n";   for (@programme) { for my $char (split //) { given ($char) { when ('H') { hello() } when ('Q') { quinne(@programme) } when ('9') { bottles() } default { die "Unknown instruction $char.\n" } # Comment this line to ignore other instructions. } } }   sub hello { print 'Hello World'; }   sub quinne { print @programme; }   sub bottles { for my $n (reverse 0 .. 99) { my $before = bottle_count($n); my $after = bottle_count($n - 1); my $action = bottle_action($n); say "\u$before of beer on the wall, $before of beer."; say "$action, $after of beer on the wall."; say q() if $n; } }   sub bottle_count { my $n = shift; given ($n) { when (-1) { return '99 bottles' } when (0) { return 'no more bottles' } when (1) { return '1 bottle' } default { return "$n bottles" } } }   sub bottle_action { my $n = shift; return 'Take one down and pass it around' if $n > 0; return 'Go to the store and buy some more'; }
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
#Nim
Nim
import strutils, strscans   type Rule = object pattern: string # Input pattern. replacement: string # Replacement string (may be empty). terminating: bool # "true" if terminating rule.   #---------------------------------------------------------------------------------------------------   func parse(rules: string): seq[Rule] = ## Parse a rule set to build a sequence of rules.   var linecount = 0 for line in rules.splitLines():   inc linecount if line.startsWith('#'): continue if line.strip.len == 0: continue   # Scan the line. var pat, rep: string var terminating = false if not line.scanf("$+ -> $*", pat, rep): raise newException(ValueError, "Invalid rule at line " & $linecount)   if rep.startsWith('.'): # Terminating rule. rep = rep[1..^1] terminating = true   result.add(Rule(pattern: pat, replacement: rep, terminating: terminating))   #---------------------------------------------------------------------------------------------------   func apply(text: string; rules: seq[Rule]): string = ## Apply a set of rules to a text and return the result.   result = text var changed = true   while changed: changed = false # Try to apply the rules in sequence. for rule in rules: if result.find(rule.pattern) >= 0: # Found a rule to apply. result = result.replace(rule.pattern, rule.replacement) if rule.terminating: return changed = true break   #———————————————————————————————————————————————————————————————————————————————————————————————————   const SampleTexts = ["I bought a B of As from T S.", "I bought a B of As from T S.", "I bought a B of As W my Bgage from T S.", "_1111*11111_", "000000A000000"]   const Rulesets = [   #................................................   """# 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""",   #................................................   """# Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule""",   #................................................   """# 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""",   #................................................   """### 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 _+_ -> """,   #................................................   """# 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"""   ]   for n, ruleset in RuleSets: let rules = ruleset.parse() echo SampleTexts[n].apply(rules)
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
#OCaml
OCaml
(* Useful for resource cleanup (such as filehandles) *) let try_finally x f g = try let res = f x in g x; res with e -> g x; raise e   (* Substitute string 'b' for first occurance of regexp 'a' in 's'; * Raise Not_found if there was no occurance of 'a'. *) let subst a b s = ignore (Str.search_forward a s 0); (* to generate Not_found *) Str.replace_first a b s   let parse_rules cin = let open Str in let rule = regexp "\\(.+\\)[ \t]+->[ \t]+\\(.*\\)" in let leader s c = String.length s > 0 && s.[0] = c in let parse_b s = if leader s '.' then (string_after s 1,true) else (s,false) in let rec parse_line rules = try let s = input_line cin in if leader s '#' then parse_line rules else if string_match rule s 0 then let a = regexp_string (matched_group 1 s) in let b,terminate = parse_b (matched_group 2 s) in parse_line ((a,b,terminate)::rules) else failwith ("parse error: "^s) with End_of_file -> rules in List.rev (parse_line [])   let rec run rules text = let rec apply s = function | [] -> s | (a,b,term)::next -> try let s' = subst a b s in if term then s' else run rules s' with Not_found -> apply s next in apply text rules   let _ = if Array.length Sys.argv <> 2 then print_endline "Expecting one argument: a filename where rules can be found." else let rules = try_finally (open_in Sys.argv.(1)) parse_rules close_in in (* Translate lines read from stdin, until EOF *) let rec translate () = print_endline (run rules (input_line stdin)); translate () in try translate () with End_of_file -> ()
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#Phix
Phix
constant U0 = 0, U1 = 1 integer count = 0 procedure baz() count += 1 if count=1 then throw(U0,{{"any",{{"thing"},"you"}},"like"}) else throw(U1) end if end procedure procedure bar() baz() end procedure procedure foo() for i=1 to 2 do try bar() catch e if e[E_CODE]=U0 then ?e[E_USER] else throw(e) -- (terminates) end if end try puts(1,"still running...\n") end for puts(1,"not still running...\n") end procedure foo()
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#PicoLisp
PicoLisp
(de foo () (for Tag '(U0 U1) (catch 'U0 (bar Tag) ) ) )   (de bar (Tag) (baz Tag) )   (de baz (Tag) (throw Tag) )   (mapc trace '(foo bar baz)) (foo)
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
#langur
langur
# do something throw "not a math exception"   catch .e { if .e["cat"] == "math" { # change result... } else { # rethrow the exception throw } } else { # no exception ... }
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
#Lasso
Lasso
protect => { handle_error => { // do something else } fail(-1,'Oops') }
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
#FutureBasic
FutureBasic
  include "ConsoleWindow"   local fn DoUnixCommand( cmd as str255 ) dim as str255 s   open "Unix", 2, cmd while ( not eof(2) ) line input #2, s print s wend close 2 end fn   fn DoUnixCommand( "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
#Gambas
Gambas
Public Sub Main()   Shell "ls -aul"   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
#Genie
Genie
[indent=4] /* Execute system command, in Genie   valac executeSystemCommand.gs ./executeSystemCommand */   init try // Non Blocking Process.spawn_command_line_async("ls") except e : SpawnError stderr.printf("%s\n", e.message)
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
#AutoHotkey
AutoHotkey
MsgBox % factorial(4)   factorial(n) { result := 1 Loop, % n result *= A_Index Return result }
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
#Modula-3
Modula-3
MODULE Expt EXPORTS Main;   IMPORT IO, Fmt;   PROCEDURE IntExpt(arg, exp: INTEGER): INTEGER = VAR result := 1; BEGIN FOR i := 1 TO exp DO result := result * arg; END; RETURN result; END IntExpt;   PROCEDURE RealExpt(arg: REAL; exp: INTEGER): REAL = VAR result := 1.0; BEGIN IF exp < 0 THEN FOR i := exp TO -1 DO result := result / arg; END; ELSE FOR i := 1 TO exp DO result := result * arg; END; END; RETURN result; END RealExpt;   BEGIN IO.Put("2 ^ 4 = " & Fmt.Int(IntExpt(2, 4)) & "\n"); IO.Put("2.5 ^ 4 = " & Fmt.Real(RealExpt(2.5, 4)) & "\n"); END Expt.
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Scheme
Scheme
  (define-syntax if2 (syntax-rules () ((if2 cond1 cond2 both-true first-true second-true none-true) (let ((c2 cond2)) (if cond1 (if c2 both-true first-true) (if c2 second-true none-true))))))  
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Seed7
Seed7
$ include "seed7_05.s7i";   $ syntax expr: .if.().().then.().else1.().else2.().else3.().end.if is -> 25;   const proc: if (in boolean: cond1) (in boolean: cond2) then (in proc: statements1) else1 (in proc: statements2) else2 (in proc: statements3) else3 (in proc: statements4) end if is func begin if cond1 then if cond2 then statements1; else statements2; end if; elsif cond2 then statements3; else statements4; end if; end func;   const proc: main is func begin if TRUE FALSE then writeln("error TRUE TRUE"); else1 writeln("TRUE FALSE"); else2 writeln("error FALSE TRUE"); else3 writeln("error FALSE FALSE"); end if; end func;
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
#SenseTalk
SenseTalk
repeat 100 put "" into output if the counter is a multiple of 3 then put "Fizz" after output end if if the counter is a multiple of 5 then put "Buzz" after output end if if output is empty then put the counter into output end if put output end repeat
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. The routine should be used to: Show the first twenty primes. Show the primes between 100 and 150. Show the number of primes between 7,700 and 8,000. Show the 10,000th prime. Show output on this page. Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). Note 3:The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency). Reference Prime Numbers. Website with large count of primes.
#Ruby
Ruby
require "prime"   puts Prime.take(20).join(", ") puts Prime.each(150).drop_while{|pr| pr < 100}.join(", ") puts Prime.each(8000).drop_while{|pr| pr < 7700}.count puts Prime.take(10_000).last
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.
#Burlesque
Burlesque
  ".""X"r~"-""\/^^{vvvv}c!!!-.256.%{vvvv}c!sa\/"r~"+""\/^^{vvvv}c!!!+. 256.%{vvvv}c!sa\/"r~"[""{"r~"]""}{\/^^{vvvv}c!!!}w!"r~">""+."r~"<"" -."r~"X""\/^^{vvvv}c!!!L[+]\/+]\/+]^^3\/.+1RAp^\/+]\/[-1RA^^-]\/[-\/ "r~"\'\'1 128r@{vv0}m[0"\/.+pse!vvvv<-sh  
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.
#COBOL
COBOL
identification division. program-id. evolutionary-program. data division. working-storage section. 01 evolving-strings. 05 target pic a(28) value 'METHINKS IT IS LIKE A WEASEL'. 05 parent pic a(28). 05 offspring-table. 10 offspring pic a(28) occurs 50 times. 01 fitness-calculations. 05 fitness pic 99. 05 highest-fitness pic 99. 05 fittest pic 99. 01 parameters. 05 character-set pic a(27) value 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '. 05 size-of-generation pic 99 value 50. 05 mutation-rate pic 99 value 5. 01 counters-and-working-variables. 05 character-position pic 99. 05 randomization. 10 random-seed pic 9(8). 10 random-number pic 99. 10 random-letter pic 99. 05 generation pic 999. 05 child pic 99. 05 temporary-string pic a(28). procedure division. control-paragraph. accept random-seed from time. move function random(random-seed) to random-number. perform random-letter-paragraph, varying character-position from 1 by 1 until character-position is greater than 28. move temporary-string to parent. move zero to generation. perform output-paragraph. perform evolution-paragraph, varying generation from 1 by 1 until parent is equal to target. stop run. evolution-paragraph. perform mutation-paragraph varying child from 1 by 1 until child is greater than size-of-generation. move zero to highest-fitness. move 1 to fittest. perform check-fitness-paragraph varying child from 1 by 1 until child is greater than size-of-generation. move offspring(fittest) to parent. perform output-paragraph. output-paragraph. display generation ': ' parent. random-letter-paragraph. move function random to random-number. divide random-number by 3.80769 giving random-letter. add 1 to random-letter. move character-set(random-letter:1) to temporary-string(character-position:1). mutation-paragraph. move parent to temporary-string. perform character-mutation-paragraph, varying character-position from 1 by 1 until character-position is greater than 28. move temporary-string to offspring(child). character-mutation-paragraph. move function random to random-number. if random-number is less than mutation-rate then perform random-letter-paragraph. check-fitness-paragraph. move offspring(child) to temporary-string. perform fitness-paragraph. fitness-paragraph. move zero to fitness. perform character-fitness-paragraph, varying character-position from 1 by 1 until character-position is greater than 28. if fitness is greater than highest-fitness then perform fittest-paragraph. character-fitness-paragraph. if temporary-string(character-position:1) is equal to target(character-position:1) then add 1 to fitness. fittest-paragraph. move fitness to highest-fitness. move child to fittest.
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
#LFE
LFE
  (defun fib ((0) 0) ((1) 1) ((n) (+ (fib (- n 1)) (fib (- n 2)))))  
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Phix
Phix
with javascript_semantics -- copied from 99_Bottles_of_Beer constant ninetynine = 2 -- (set this to 9 for testing) function bottles(integer count) if count=0 then return "no more bottles" elsif count=1 then return "1 bottle" end if if count=-1 then count = ninetynine end if return sprintf("%d bottles",count) end function function bob(integer count) return bottles(count)&" of beer" end function function up1(string bob) -- Capitalise sentence start (needed just the once, "no more"=>"No more") bob[1] = upper(bob[1]) return bob end function procedure ninetyninebottles() string thus = bob(ninetynine), that = "Take one down, pass it around,\n" for i=ninetynine to 0 by -1 do puts(1,up1(thus)&" on the wall,\n") puts(1,thus&".\n") if i=0 then that = "Go to the store, buy some more,\n" elsif i=1 then that[6..8] = "it" end if thus = bob(i-1) puts(1,that&thus&" on the wall.\n\n") end for -- if getc(0) then end if end procedure -- the interpreter procedure hq9(string code) integer accumulator = 0 for i=1 to length(code) do switch(upper(code[i])) case 'H': printf(1,"Hello, world!\n") case 'Q': printf(1,"%s\n", code); case '9': ninetyninebottles() case '+': accumulator += 1 end switch end for end procedure hq9("h9+HqQ+Qq")
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
#Perl
Perl
@ARGV == 1 or die "Please provide exactly one source file as an argument.\n"; open my $source, '<', $ARGV[0] or die "I couldn't open \"$ARGV[0]\" for reading. ($!.)\n"; my @rules; while (<$source>) {/\A#/ and next; my @a = /(.*?)\s+->\s+(\.?)(.*)/ or die "Syntax error: $_"; push @rules, \@a;} close $source;   my $input = do {local $/; <STDIN>;};   OUTER: {foreach (@rules) {my ($from, $terminating, $to) = @$_; $input =~ s/\Q$from\E/$to/ and ($terminating ? last OUTER : redo OUTER);}}   print $input;
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#PL.2FI
PL/I
  /* Exceptions: Catch an exception thrown in a nested call */ test: proc options (main); /* 8/1/2011 */ declare (m, n) fixed initial (2); declare (U0, U1) condition;   foo: procedure () returns (fixed); on condition(U0) snap begin; put list ('Raised condition U0 in function <bar>.'); put skip; end; m = bar(); m = bar(); return (m); end foo;   bar: procedure () returns (fixed); n = n + 1; return (baz()); return (n); end bar; baz: procedure () returns (fixed); declare first bit(1) static initial ('1'b); n = n + 1; if first then do; first = '0'b; signal condition(U0); end; else signal condition(U1); return (n); end baz;   m = foo(); end test;  
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#Python
Python
class U0(Exception): pass class U1(Exception): pass   def foo(): for i in range(2): try: bar(i) except U0: print("Function foo caught exception U0")   def bar(i): baz(i) # Nest those calls   def baz(i): raise U1 if i else U0   foo()
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#Quackery
Quackery
[ this ] is U0   [ this ] is U1   [ 0 = iff U0 else U1 message put bail ] is baz ( n --> )   [ baz ] is bar ( n --> )   [ 2 times [ i^ 1 backup bar bailed if [ message share U0 oats iff [ say "Exception U0 raised." cr echostack $ "Press enter to continue" input drop message release drop ] else [ drop bail ] ] ] ] is foo
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
#Lingo
Lingo
-- parent script "ErrorHandler"   on alertHook (me, errorType, errorMessage, alertType) if alertType=#alert then return 0 -- ignore programmatic alerts   -- log error in file "error.log" fn = _movie.path&"error.log" fp = xtra("fileIO").new() fp.openFile(fn, 2) if fp.status() = -37 then fp.createFile(fn) fp.openFile(fn, 2) end if fp.setPosition(fp.getLength()) fp.writeString(_system.date() && _system.time() && errorType & ": " & errorMessage & RETURN) fp.closeFile()   return 1 -- continues movie playback, no error dialog 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
#Logo
Logo
to div.checked :a :b if :b = 0 [(throw "divzero 0)] output :a / :b end to div.safely :a :b output catch "divzero [div.checked :a :b] 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
#gnuplot
gnuplot
!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
#Go
Go
package main   import ( "log" "os" "os/exec" )   func main() { cmd := exec.Command("ls", "-l") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
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
#AutoIt
AutoIt
;AutoIt Version: 3.2.10.0 MsgBox (0,"Factorial",factorial(6)) Func factorial($int) If $int < 0 Then Return 0 EndIf $fact = 1 For $i = 1 To $int $fact = $fact * $i Next Return $fact EndFunc
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
#Nemerle
Nemerle
using System;   macro @^ (val, pow : int) { <[ Math.Pow($val, $pow) ]> }
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
#Nim
Nim
proc `^`[T: float|int](base: T; exp: int): T = var (base, exp) = (base, exp) result = 1   if exp < 0: when T is int: if base * base != 1: return 0 elif (exp and 1) == 0: return 1 else: return base else: base = 1.0 / base exp = -exp   while exp != 0: if (exp and 1) != 0: result *= base exp = exp shr 1 base *= base   echo "2^6 = ", 2^6 echo "2^-6 = ", 2 ^ -6 echo "2.71^6 = ", 2.71^6 echo "2.71^-6 = ", 2.71 ^ -6
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Shen
Shen
(defmacro branch-if-macro [branch-if Cond1 Cond2 Both Fst Snd None] -> [if Cond1 [if Cond2 Both Fst] [if Cond2 Snd None]])
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Sidef
Sidef
class if2(cond1, cond2) { method then(block) { # both true if (cond1 && cond2) { block.run; } return self; } method else1(block) { # first true if (cond1 && !cond2) { block.run; } return self; } method else2(block) { # second true if (cond2 && !cond1) { block.run; } return self; } method else(block) { # none true if (!cond1 && !cond2) { block.run; } return self; } }   if2(false, true).then { say "if2"; }.else1 { say "else1"; }.else2 { say "else2"; # <- this gets printed }.else { say "else" }
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
#SequenceL
SequenceL
import <Utilities/Conversion.sl>; import <Utilities/Sequence.sl>;   main(args(2)) := let result[i] := "FizzBuzz" when i mod 3 = 0 and i mod 5 = 0 else "Fizz" when i mod 3 = 0 else "Buzz" when i mod 5 = 0 else intToString(i) foreach i within 1 ... 100; in delimit(result, '\n');
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. The routine should be used to: Show the first twenty primes. Show the primes between 100 and 150. Show the number of primes between 7,700 and 8,000. Show the 10,000th prime. Show output on this page. Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). Note 3:The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency). Reference Prime Numbers. Website with large count of primes.
#Rust
Rust
mod pagesieve;   use pagesieve::{count_primes_paged, primes_paged};   fn main() { println!("First 20 primes:\n {:?}", primes_paged().take(20).collect::<Vec<_>>()); println!("Primes between 100 and 150:\n {:?}", primes_paged().skip_while(|&x| x < 100) .take_while(|&x| x < 150) .collect::<Vec<_>>()); let diff = count_primes_paged(8000) - count_primes_paged(7700); println!("There are {} primes between 7,700 and 8,000", diff); // rust enumerations are zero base, so need to subtract 1!!! println!("The 10,000th prime is {}", primes_paged().nth(10_000 - 1).unwrap()); }
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.
#C
C
(ns brainfuck)   (def ^:dynamic *input*)   (def ^:dynamic *output*)   (defrecord Data [ptr cells])   (defn inc-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] inc))))   (defn dec-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] dec))))   (defn inc-cell [next-cmd] (fn [data] (next-cmd (update-in data [:cells (:ptr data)] (fnil inc 0)))))   (defn dec-cell [next-cmd] (fn [data] (next-cmd (update-in data [:cells (:ptr data)] (fnil dec 0)))))   (defn output-cell [next-cmd] (fn [data] (set! *output* (conj *output* (get (:cells data) (:ptr data) 0))) (next-cmd data)))   (defn input-cell [next-cmd] (fn [data] (let [[input & rest-input] *input*] (set! *input* rest-input) (next-cmd (update-in data [:cells (:ptr data)] input)))))   (defn if-loop [next-cmd loop-cmd] (fn [data] (next-cmd (loop [d data] (if (zero? (get (:cells d) (:ptr d) 0)) d (recur (loop-cmd d)))))))   (defn terminate [data] data)   (defn split-cmds [cmds] (letfn [(split [[cmd & rest-cmds] loop-cmds] (when (nil? cmd) (throw (Exception. "invalid commands: missing ]"))) (case cmd \[ (let [[c l] (split-cmds rest-cmds)] (recur c (str loop-cmds "[" l "]"))) \] [(apply str rest-cmds) loop-cmds] (recur rest-cmds (str loop-cmds cmd))))] (split cmds "")))   (defn compile-cmds [[cmd & rest-cmds]] (if (nil? cmd) terminate (case cmd \> (inc-ptr (compile-cmds rest-cmds)) \< (dec-ptr (compile-cmds rest-cmds)) \+ (inc-cell (compile-cmds rest-cmds)) \- (dec-cell (compile-cmds rest-cmds)) \. (output-cell (compile-cmds rest-cmds)) \, (input-cell (compile-cmds rest-cmds)) \[ (let [[cmds loop-cmds] (split-cmds rest-cmds)] (if-loop (compile-cmds cmds) (compile-cmds loop-cmds))) \] (throw (Exception. "invalid commands: missing [")) (compile-cmds rest-cmds))))   (defn compile-and-run [cmds input] (binding [*input* input *output* []] (let [compiled-cmds (compile-cmds cmds)] (println (compiled-cmds (Data. 0 {})))) (println *output*) (println (apply str (map char *output*)))))  
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.
#ColdFusion
ColdFusion
  <Cfset theString = 'METHINKS IT IS LIKE A WEASEL'> <cfparam name="parent" default=""> <Cfset theAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "> <Cfset fitness = 0> <Cfset children = 3> <Cfset counter = 0>   <Cfloop from="1" to="#children#" index="child"> <Cfparam name="child#child#" default=""> <Cfparam name="fitness#child#" default=0> </Cfloop>   <Cfloop condition="fitness lt 1">   <Cfset oldparent = parent> <Cfset counter = counter + 1>   <cfloop from="1" to="#children#" index="child"> <Cfset thischild = ''>   <Cfloop from="1" to="#len(theString)#" index="i"> <cfset Mutate = Mid(theAlphabet, RandRange(1, 28), 1)> <cfif fitness eq 0> <Cfset thischild = thischild & mutate> <Cfelse>   <Cfif Mid(theString, i, 1) eq Mid(variables["child" & child], i, 1)> <Cfset thischild = thischild & Mid(variables["child" & child], i, 1)> <Cfelse> <cfset MutateChance = 1/fitness> <Cfset MutateChanceRand = rand()> <Cfif MutateChanceRand lte MutateChance> <Cfset thischild = thischild & mutate> <Cfelse> <Cfset thischild = thischild & Mid(variables["child" & child], i, 1)> </Cfif> </Cfif>   </cfif> </Cfloop>   <Cfset variables["child" & child] = thischild>   </cfloop>   <cfloop from="1" to="#children#" index="child"> <Cfset thisChildFitness = 0> <Cfloop from="1" to="#len(theString)#" index="i"> <Cfif Mid(variables["child" & child], i, 1) eq Mid(theString, i, 1)> <Cfset thisChildFitness = thisChildFitness + 1> </Cfif> </Cfloop>   <Cfset variables["fitness" & child] = (thisChildFitness)/len(theString)>   <Cfif variables["fitness" & child] gt fitness> <Cfset fitness = variables["fitness" & child]> <Cfset parent = variables["child" & child]> </Cfif>   </cfloop>   <Cfif parent neq oldparent> <Cfoutput>###counter# #numberformat(fitness*100, 99)#% fit: #parent#<br></Cfoutput><cfflush> </Cfif>   </Cfloop>  
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
#Liberty_BASIC
Liberty BASIC
  for i = 0 to 15 print fiboR(i),fiboI(i) next i   function fiboR(n) if n <= 1 then fiboR = n else fiboR = fiboR(n-1) + fiboR(n-2) end if end function   function fiboI(n) a = 0 b = 1 for i = 1 to n temp = a + b a = b b = temp next i fiboI = a end function  
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#php
php
  /* H Prints "Hello, world!" Q Prints the entire text of the source code file. 9 Prints the complete canonical lyrics to "99 Bottles of Beer on the Wall" + Increments the accumulator. */ $accumulator = 0; echo 'HQ9+: '; $program = trim(fgets(STDIN));   foreach (str_split($program) as $chr) { switch ($chr) { case 'H': case 'h': printHelloWorld(); break; case 'Q': case 'q': printSource($program); break; case '9': print99Bottles(); break; case '+': $accumulator = incrementAccumulator($accumulator); break; default: printError($chr); } }   function printHelloWorld() { echo 'Hello, world!'. PHP_EOL; }   function printSource($program) { echo var_export($program, true) . PHP_EOL; }   function print99Bottles() { $n = 99; while($n >= 1) { echo $n; echo ' Bottles of Beer on the Wall '; echo $n; echo ' bottles of beer, take one down pass it around '; echo $n-1; echo ' bottles of beer on the wall.'. PHP_EOL; $n--; } }   function incrementAccumulator($accumulator) { return ++$accumulator; }   function printError($chr) { echo "Invalid input: ". $chr; }
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
#Phix
Phix
procedure markov(string rules, input, expected) sequence subs = {}, reps = {} sequence lines = split(substitute(rules,'\t',' '),'\n') for i=1 to length(lines) do string li = lines[i] if length(li) and li[1]!='#' then integer k = match(" -> ",li) if k then subs = append(subs,trim(li[1..k-1])) reps = append(reps,trim(li[k+4..$])) end if end if end for string res = input bool term = false while 1 do bool found = false for i=1 to length(subs) do string sub = subs[i] integer k = match(sub,res) if k then found = true string rep = reps[i] if length(rep) and rep[1]='.' then rep = rep[2..$] term = true end if res[k..k+length(sub)-1] = rep exit end if if term then exit end if end for if term or not found then exit end if end while ?{input,res,iff(res=expected?"ok":"**ERROR**")} end procedure constant ruleset1 = """ # 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""" markov(ruleset1,"I bought a B of As from T S.","I bought a bag of apples from my brother.") constant ruleset2 = """ # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule""" markov(ruleset2,"I bought a B of As from T S.","I bought a bag of apples from T shop.") constant ruleset3 = """ # 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""" markov(ruleset3,"I bought a B of As W my Bgage from T S.","I bought a bag of apples with my money from T shop.") constant ruleset4 = """ ### 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 _+_ -> """ markov(ruleset4,"_1111*11111_","11111111111111111111") constant ruleset5 = """ # 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 """ markov(ruleset5,"000000A000000","00011H1111000")
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#R
R
  number_of_calls_to_baz <- 0   foo <- function() { for(i in 1:2) tryCatch(bar()) }   bar <- function() baz()   baz <- function() { e <- simpleError(ifelse(number_of_calls_to_baz > 0, "U1", "U0")) assign("number_of_calls_to_baz", number_of_calls_to_baz + 1, envir=globalenv()) stop(e) }  
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#Racket
Racket
  #lang racket   (define-struct (exn:U0 exn) ()) (define-struct (exn:U1 exn) ())   (define (foo) (for ([i 2]) (with-handlers ([exn:U0? (λ(_) (displayln "Function foo caught exception U0"))]) (bar i))))   (define (bar i) (baz i))   (define (baz i) (if (= i 0) (raise (make-exn:U0 "failed 0" (current-continuation-marks))) (raise (make-exn:U1 "failed 1" (current-continuation-marks)))))   (foo)  
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#Raku
Raku
sub foo() { for 0..1 -> $i { bar $i; CATCH { when /U0/ { say "Function foo caught exception U0" } } } }   sub bar($i) { baz $i }   sub baz($i) { die "U$i" }   foo;
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
#Logtalk
Logtalk
  :- object(exceptions).   :- public(double/2). double(X, Y) :- catch(double_it(X,Y), Error, handler(Error, Y)).   handler(error(not_a_number(X), logtalk(This::double(X,Y), Sender)), Y) :- % try to fix the error and resume computation; % if not possible, rethrow the exception ( catch(number_codes(Nx, X), _, fail) -> double_it(Nx, Y) ; throw(error(not_a_number(X), logtalk(This::double(X,Y), Sender))) ).   double_it(X, Y) :- ( number(X) -> Y is 2*X ; this(This), sender(Sender), throw(error(not_a_number(X), logtalk(This::double(X,Y), Sender))) ).   :- end_object.  
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
#Lua
Lua
  error("Something bad happened!")  
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
#Groovy
Groovy
println "ls -la".execute().text
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
#GUISS
GUISS
Start,Programs,Accessories,MSDOS Prompt,Type:dir[enter]
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
#Avail
Avail
Assert: 7! = 5040;
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
#Objeck
Objeck
class Exp { function : Main(args : String[]) ~ Nil { Pow(2,30)->PrintLine(); Pow(2.0,30)->PrintLine(); Pow(2.0,-2)->PrintLine(); }   function : native : Pow(base : Float, exp : Int) ~ Float { if(exp < 0) { return 1 / base->Power(exp * -1.0); };   ans := 1.0; while(exp > 0) { ans *= base; exp -= 1; };   return ans; } }
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Smalltalk
Smalltalk
or:condition2 ifBoth:bothBlk ifFirst:firstBlk ifSecond:scndBlk ifNone:noneBlk "I know for sure, that I am true..." ^ condition2 ifTrue:bothBlk ifFalse:firstBlk
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Standard_ML
Standard ML
(* Languages with pattern matching ALREADY HAVE THIS! *)   fun myfunc (pred1, pred2) = case (pred1, pred2) of (true, true) => print ("(true, true)\n") | (true, false) => print ("(true, false)\n") | (false, true) => print ("(false, true)\n") | (false, false) => print ("(false, false)\n");   myfunc (true, true); myfunc (true, false); myfunc (false, true); myfunc (false, false);
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
#Shale
Shale
#!/usr/local/bin/shale   string library   r var i var i 1 = { i 100 <= } { r "" = i 3 % 0 == { r r "fizz" concat string::() = } ifthen i 5 % 0 == { r r "buzz" concat string::() = } ifthen r "" equals string::() { i } { r } if i "%3d: %p\n" printf i++ } while
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. The routine should be used to: Show the first twenty primes. Show the primes between 100 and 150. Show the number of primes between 7,700 and 8,000. Show the 10,000th prime. Show output on this page. Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). Note 3:The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency). Reference Prime Numbers. Website with large count of primes.
#Seed7
Seed7
$ include "seed7_05.s7i";   const func boolean: isPrime (in integer: number) is func result var boolean: prime is FALSE; local var integer: count is 2; begin if number = 2 then prime := TRUE; elsif number > 2 then while number rem count <> 0 and count * count <= number do incr(count); end while; prime := number rem count <> 0; end if; end func;   var integer: currentPrime is 1; var integer: primeNum is 0;   const func integer: getPrime is func result var integer: nextPrime is 0; begin repeat incr(currentPrime); until isPrime(currentPrime); nextPrime := currentPrime; incr(primeNum); end func;   const proc: main is func local var integer: aPrime is 0; var integer: count is 0; begin write("First twenty primes:"); while primeNum < 20 do write(" " <& getPrime); end while; writeln; repeat aPrime := getPrime; until aPrime >= 100; write("Primes between 100 and 150:"); while aPrime <= 150 do write(" " <& aPrime); aPrime := getPrime; end while; writeln; repeat aPrime := getPrime; until aPrime >= 7700; while aPrime <= 8000 do incr(count); aPrime := getPrime; end while; writeln("Number of primes between 7,700 and 8,000: " <& count); repeat aPrime := getPrime; until primeNum = 9999; # discard up to and including the 9,999 prime! writeln("The 10,000th prime: " <& getPrime); end func;
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.
#C.23
C#
(ns brainfuck)   (def ^:dynamic *input*)   (def ^:dynamic *output*)   (defrecord Data [ptr cells])   (defn inc-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] inc))))   (defn dec-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] dec))))   (defn inc-cell [next-cmd] (fn [data] (next-cmd (update-in data [:cells (:ptr data)] (fnil inc 0)))))   (defn dec-cell [next-cmd] (fn [data] (next-cmd (update-in data [:cells (:ptr data)] (fnil dec 0)))))   (defn output-cell [next-cmd] (fn [data] (set! *output* (conj *output* (get (:cells data) (:ptr data) 0))) (next-cmd data)))   (defn input-cell [next-cmd] (fn [data] (let [[input & rest-input] *input*] (set! *input* rest-input) (next-cmd (update-in data [:cells (:ptr data)] input)))))   (defn if-loop [next-cmd loop-cmd] (fn [data] (next-cmd (loop [d data] (if (zero? (get (:cells d) (:ptr d) 0)) d (recur (loop-cmd d)))))))   (defn terminate [data] data)   (defn split-cmds [cmds] (letfn [(split [[cmd & rest-cmds] loop-cmds] (when (nil? cmd) (throw (Exception. "invalid commands: missing ]"))) (case cmd \[ (let [[c l] (split-cmds rest-cmds)] (recur c (str loop-cmds "[" l "]"))) \] [(apply str rest-cmds) loop-cmds] (recur rest-cmds (str loop-cmds cmd))))] (split cmds "")))   (defn compile-cmds [[cmd & rest-cmds]] (if (nil? cmd) terminate (case cmd \> (inc-ptr (compile-cmds rest-cmds)) \< (dec-ptr (compile-cmds rest-cmds)) \+ (inc-cell (compile-cmds rest-cmds)) \- (dec-cell (compile-cmds rest-cmds)) \. (output-cell (compile-cmds rest-cmds)) \, (input-cell (compile-cmds rest-cmds)) \[ (let [[cmds loop-cmds] (split-cmds rest-cmds)] (if-loop (compile-cmds cmds) (compile-cmds loop-cmds))) \] (throw (Exception. "invalid commands: missing [")) (compile-cmds rest-cmds))))   (defn compile-and-run [cmds input] (binding [*input* input *output* []] (let [compiled-cmds (compile-cmds cmds)] (println (compiled-cmds (Data. 0 {})))) (println *output*) (println (apply str (map char *output*)))))  
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.
#Commodore_BASIC
Commodore BASIC
10 N=100:P=0.05:TI$="000000" 20 Z$="METHINKS IT IS LIKE A WEASEL" 30 L=LEN(Z$) 40 DIMX(N,L) 50 FORI=1TOL 60 IFMID$(Z$,I,1)=" "THENX(0,I)=0:GOTO80 70 X(0,I)=ASC(MID$(Z$,I))-64 80 NEXT 90 FORK=1TON:FORI=1TOL:X(K,I)=INT(RND(0)*27):NEXT:NEXT 100 S=-100:B=0 110 K=B:GOSUB300 120 FORK=1TON:IFK=BTHEN150 130 FORI=1TOL:IFRND(.)<PTHENX(K,I)=INT(RND(0)*27) 140 NEXT 150 NEXT 160 S=-100:B=0 170 FORK=1TON 180 F=0:FORI=1TOL:IFX(K,I)<>X(0,I)THENF=F-1:IFF<STHENI=L 190 NEXT:IFF>STHENS=F:B=K 200 NEXT 210 PRINT"BEST:"B;"SCORE:"S 220 IFS=0THEN270 230 FORK=1TON:IFK=BTHEN250 240 FORI=1TOL:X(K,I)=X(B,I):NEXT 250 NEXT 260 GOTO110 270 PRINT"WE HAVE A WEASEL!":K=B:GOSUB300 280 PRINT"TIME:"TI$:END 300 FORI=1TOL:IFX(K,I)THENPRINTCHR$(64+X(K,I));:GOTO320 310 PRINT" "; 320 NEXT:PRINT"<":RETURN
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
#Lingo
Lingo
on fib (n) if n<2 then return n return fib(n-1)+fib(n-2) end
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#PicoLisp
PicoLisp
(de hq9+ (Code) (let Accu 0 (for C (chop Code) (case C ("H" (prinl "Hello, world")) ("Q" (prinl Code)) ("9" (for (N 99 (gt0 N)) (prinl N " bottles of beer on the wall") (prinl N " bottles of beer") (prinl "Take one down, pass it around") (prinl (dec 'N) " bottles of beer on the wall") (prinl) ) ) ("+" (inc 'Accu)) ) ) Accu ) )
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#PowerShell
PowerShell
  function Invoke-HQ9PlusInterpreter ([switch]$Global) { $sb = New-Object -TypeName System.Text.StringBuilder   for ($i = 99; $i -gt 2; $i--) { $sb.Append((("{0,2} bottles of beer on the wall, " + "{0,2} bottles of beer! Take one down, pass it around, " + "{1,2} bottles of beer on the wall.`n") -f $i, ($i - 1))) | Out-Null } $sb.Append((" 2 bottles of beer on the wall, " + " 2 bottles of beer! Take one down, pass it around, " + " 1 bottle of beer on the wall.`n")) | Out-Null $sb.Append((" 1 bottle of beer on the wall, " + " 1 bottle of beer! Take one down, pass it around...`n")) | Out-Null $sb.Append(("No more bottles of beer on the wall, No more bottles of beer!`n" + "Go to the store and get us some more, 99 bottles of beer on the wall!")) | Out-Null   $99BottlesOfBeer = $sb.ToString()   $helloWorld = "Hello, world!"   if ($Global) {New-Variable -Name "+" -Value 0 -Scope Global -ErrorAction SilentlyContinue}   Write-Host "Press Ctrl-C or Enter nothing to exit." -ForegroundColor Cyan   while ($code -ne "") { $code = Read-Host -Prompt "HQ9+"   ($code.ToCharArray() | Select-String -Pattern "[HQ9+]").Matches.Value | ForEach-Object { switch ($_) { "H" {$helloWorld; break} "Q" {$code; break} "9" {$99BottlesOfBeer; break} "+" {if ($Global) {${global:+}++}} } } } }   Set-Alias -Name HQ9+ -Value Invoke-HQ9PlusInterpreter  
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
#PHP
PHP
<?php   function markov($text, $ruleset) { $lines = explode(PHP_EOL, $ruleset); $rules = array(); foreach ($lines AS $line) { $spc = "[\t ]+"; if (empty($line) OR preg_match('/^#/', $line)) { continue; } elseif (preg_match('/^(.+)' . $spc . '->' . $spc . '(\.?)(.*)$/', $line, $matches)) { list($dummy, $pattern, $terminating, $replacement) = $matches; $rules[] = array( 'pattern' => trim($pattern), 'terminating' => ($terminating === '.'), 'replacement' => trim($replacement), ); } } do { $found = false; foreach ($rules AS $rule) { if (strpos($text, $rule['pattern']) !== FALSE) { $text = str_replace($rule['pattern'], $rule['replacement'], $text); if ($rule['terminating']) { return $text; } $found = true; break; } } } while($found); return $text; }   $conf = array( 1 => array( 'text' => 'I bought a B of As from T S.', 'rule' => ' # 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 ', ), 2 => array( 'text' => 'I bought a B of As from T S.', '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 ', ), 3 => array( 'text' => 'I bought a B of As W my Bgage from T S.', 'rule' => ' # 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 ', ), 4 => array( 'text' => '_1111*11111_', 'rule' => ' ### 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 _+_ -> ', ), 5 => array( 'text' => '000000A000000', 'rule' => ' # 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 ', ), 6 => array( 'text' => '101', 'rule' => ' # Another example extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm 1 -> 0| |0 -> 0|| 0 -> ', ), );   foreach ($conf AS $id => $rule) { echo 'Ruleset ', $id, ' : ', markov($rule['text'], $rule['rule']), PHP_EOL; }
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#REXX
REXX
/*REXX program creates two exceptions and demonstrates how to handle (catch) them. */ call foo /*invoke the FOO function (below). */ say 'The REXX mainline program has completed.' /*indicate that Elroy was here. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ foo: call bar; call bar /*invoke BAR function twice. */ return 0 /*return a zero to the invoker. */ /*the 1st U0 in REXX program is used.*/ U0: say 'exception U0 caught in FOO' /*handle the U0 exception. */ return -2 /*return to the invoker. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ bar: call baz /*have BAR function invoke BAZ function*/ return 0 /*return a zero to the invoker. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ baz: if symbol('BAZ#')=='LIT' then baz#=0 /*initialize the first BAZ invocation #*/ baz# = baz#+1 /*bump the BAZ invocation number by 1. */ if baz#==1 then signal U0 /*if first invocation, then raise U0 */ if baz#==2 then signal U1 /* " second " " " U1 */ return 0 /*return a 0 (zero) to the invoker.*/ /* [↓] this U0 subroutine is ignored.*/ U0: return -1 /*handle exception if not caught. */ U1: return -1 /* " " " " " */
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#Ruby
Ruby
def foo 2.times do |i| begin bar(i) rescue U0 $stderr.puts "captured exception U0" end end end   def bar(i) baz(i) end   def baz(i) raise i == 0 ? U0 : U1 end   class U0 < StandardError; end   class U1 < StandardError; end   foo
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
#M2000_Interpreter
M2000 Interpreter
  Module Errors { Module Check { Module Error1 { A=1/0 }   Try ok { Error1 } ' we get an Error, and Error$ print division by zero in module Error1 If Error or not ok then Print Error$ Error "New Error" } Try { Check } Print Error=0 ' no Error return Print Error$ ' but Error message isn't clear ' Error$ used one time, then cleared automatic } Errors Print Error$=""  
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
#Make
Make
all: false
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
#Haskell
Haskell
import System.Cmd   main = system "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
#HicEst
HicEst
SYSTEM(CoMmand='pause') SYSTEM(CoMmand='dir & pause')
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
#AWK
AWK
function fact_r(n) { if ( n <= 1 ) return 1; return n*fact_r(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
#OCaml
OCaml
let pow one mul a n = let rec g p x = function | 0 -> x | i -> g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2) in g a one n ;;   pow 1 ( * ) 2 16;; (* 65536 *) pow 1.0 ( *. ) 2.0 16;; (* 65536. *)   (* pow is not limited to exponentiation *) pow 0 ( + ) 2 16;; (* 32 *) pow "" ( ^ ) "abc " 10;; (* "abc abc abc abc abc abc abc abc abc abc " *) pow [ ] ( @ ) [ 1; 2 ] 10;; (* [1; 2; 1; 2; 1; 2; 1; 2; 1; 2; 1; 2; 1; 2; 1; 2; 1; 2; 1; 2] *)   (* Thue-Morse sequence *) Array.init 32 (fun n -> (1 - pow 1 ( - ) 0 n) lsr 1);;   (* [|0; 1; 1; 0; 1; 0; 0; 1; 1; 0; 0; 1; 0; 1; 1; 0; 1; 0; 0; 1; 0; 1; 1; 0; 0; 1; 1; 0; 1; 0; 0; 1|]   See http://en.wikipedia.org/wiki/Thue-Morse_sequence *)
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Tcl
Tcl
proc if2 {cond1 cond2 bothTrueBody firstTrueBody secondTrueBody bothFalseBody} { # Must evaluate both conditions, and should do so in order set c1 [uplevel 1 [list expr $cond1] set c2 [uplevel 1 [list expr $cond2] # Now use that to decide what to do if {$c1 && $c2} { uplevel 1 $bothTrueBody } elseif {$c1 && !$c2} { uplevel 1 $firstTrueBody } elseif {$c2 && !$c1} { uplevel 1 $secondTrueBody } else { uplevel 1 $bothFalseBody } }
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
#Shen
Shen
(define fizzbuzz 101 -> (nl) N -> (let divisible-by? (/. A B (integer? (/ A B))) (cases (divisible-by? N 15) (do (output "Fizzbuzz!~%") (fizzbuzz (+ N 1))) (divisible-by? N 3) (do (output "Fizz!~%") (fizzbuzz (+ N 1))) (divisible-by? N 5) (do (output "Buzz!~%") (fizzbuzz (+ N 1))) true (do (output (str N)) (nl) (fizzbuzz (+ N 1))))))   (fizzbuzz 1)
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. The routine should be used to: Show the first twenty primes. Show the primes between 100 and 150. Show the number of primes between 7,700 and 8,000. Show the 10,000th prime. Show output on this page. Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). Note 3:The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency). Reference Prime Numbers. Website with large count of primes.
#Sidef
Sidef
say ("First 20: ", 20.nth_prime.primes.join(' ')) say ("Between 100 and 150: ", primes(100,150).join(' ')) say (prime_count(7700,8000), " primes between 7700 and 8000") say ("10,000th prime: ", nth_prime(10_000))
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.
#C.2B.2B
C++
(ns brainfuck)   (def ^:dynamic *input*)   (def ^:dynamic *output*)   (defrecord Data [ptr cells])   (defn inc-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] inc))))   (defn dec-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] dec))))   (defn inc-cell [next-cmd] (fn [data] (next-cmd (update-in data [:cells (:ptr data)] (fnil inc 0)))))   (defn dec-cell [next-cmd] (fn [data] (next-cmd (update-in data [:cells (:ptr data)] (fnil dec 0)))))   (defn output-cell [next-cmd] (fn [data] (set! *output* (conj *output* (get (:cells data) (:ptr data) 0))) (next-cmd data)))   (defn input-cell [next-cmd] (fn [data] (let [[input & rest-input] *input*] (set! *input* rest-input) (next-cmd (update-in data [:cells (:ptr data)] input)))))   (defn if-loop [next-cmd loop-cmd] (fn [data] (next-cmd (loop [d data] (if (zero? (get (:cells d) (:ptr d) 0)) d (recur (loop-cmd d)))))))   (defn terminate [data] data)   (defn split-cmds [cmds] (letfn [(split [[cmd & rest-cmds] loop-cmds] (when (nil? cmd) (throw (Exception. "invalid commands: missing ]"))) (case cmd \[ (let [[c l] (split-cmds rest-cmds)] (recur c (str loop-cmds "[" l "]"))) \] [(apply str rest-cmds) loop-cmds] (recur rest-cmds (str loop-cmds cmd))))] (split cmds "")))   (defn compile-cmds [[cmd & rest-cmds]] (if (nil? cmd) terminate (case cmd \> (inc-ptr (compile-cmds rest-cmds)) \< (dec-ptr (compile-cmds rest-cmds)) \+ (inc-cell (compile-cmds rest-cmds)) \- (dec-cell (compile-cmds rest-cmds)) \. (output-cell (compile-cmds rest-cmds)) \, (input-cell (compile-cmds rest-cmds)) \[ (let [[cmds loop-cmds] (split-cmds rest-cmds)] (if-loop (compile-cmds cmds) (compile-cmds loop-cmds))) \] (throw (Exception. "invalid commands: missing [")) (compile-cmds rest-cmds))))   (defn compile-and-run [cmds input] (binding [*input* input *output* []] (let [compiled-cmds (compile-cmds cmds)] (println (compiled-cmds (Data. 0 {})))) (println *output*) (println (apply str (map char *output*)))))  
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.
#Common_Lisp
Common Lisp
(defun fitness (string target) "Closeness of string to target; lower number is better" (loop for c1 across string for c2 across target count (char/= c1 c2)))   (defun mutate (string chars p) "Mutate each character of string with probablity p using characters from chars" (dotimes (n (length string)) (when (< (random 1.0) p) (setf (aref string n) (aref chars (random (length chars)))))) string)   (defun random-string (chars length) "Generate a new random string consisting of letters from char and specified length" (do ((n 0 (1+ n)) (str (make-string length))) ((= n length) str) (setf (aref str n) (aref chars (random (length chars))))))   (defun evolve-string (target string chars c p) "Generate new mutant strings, and choose the most fit string" (let ((mutated-strs (list string))) (dotimes (n c) (push (mutate (copy-seq string) chars p) mutated-strs)) (reduce #'(lambda (s0 s1) (if (< (fitness s0 target) (fitness s1 target)) s0 s1)) mutated-strs)))   (defun evolve-gens (target c p) (let ((chars " ABCDEFGHIJKLMNOPQRSTUVWXYZ")) (do ((parent (random-string chars (length target)) (evolve-string target parent chars c p)) (n 0 (1+ n))) ((string= target parent) (format t "Generation ~A: ~S~%" n parent)) (format t "Generation ~A: ~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
#Lisaac
Lisaac
- fib(n : UINTEGER_32) : UINTEGER_64 <- ( + result : UINTEGER_64; (n < 2).if { result := n; } else { result := fib(n - 1) + fib(n - 2); }; result );
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#PureBasic
PureBasic
Procedure hq9plus(code.s) Protected accumulator, i, bottles For i = 1 To Len(code) Select Mid(code, i, 1) Case "h", "H" PrintN("Hello, world!") Case "q", "Q" PrintN(code) Case "9" bottles = 99 While bottles PrintN(Str(bottles) + " bottles of beer on the wall, " + Str(bottles) + " bottles of beer,") bottles - 1 PrintN("Take one down, pass it around, " + Str(bottles) + " bottles of beer on the wall.") Wend Case "+" accumulator + 1 EndSelect Next i EndProcedure   If OpenConsole() Define testCode.s = "hq9+HqQ+Qq" hq9plus(testCode)   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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
#PicoLisp
PicoLisp
(de markov (File Text) (use (@A @Z R) (let Rules (make (in File (while (skip "#") (when (match '(@A " " "-" ">" " " @Z) (replace (line) "@" "#")) (link (cons (clip @A) (clip @Z))) ) ) ) ) (setq Text (chop Text)) (pack (loop (NIL (find '((R) (match (append '(@A) (car R) '(@Z)) Text)) Rules ) Text ) (T (= "." (cadr (setq R @))) (append @A (cddr R) @Z) ) (setq Text (append @A (cdr R) @Z)) ) ) ) ) )
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
#Prolog
Prolog
:- module('markov.pl', [markov/3, apply_markov/3]).   :- use_module(library(lambda)).   apply_markov(Rules, Sentence, Replacement) :- maplist(\X^Y^(atom_chars(X, Ch), phrase(markov(Y), Ch, [])), Rules, TmpRules), % comments produce empty rules exclude(=([]), TmpRules, LstRules),   atom_chars(Sentence, L), apply_rules(L, LstRules, R), atom_chars(Replacement, R).   apply_rules(In, Rules, Out ) :- apply_one_rule(In, Rules, Out1, Keep_On), ( Keep_On = false -> Out = Out1 ; apply_rules(Out1, Rules, Out)).     apply_one_rule(In, [Rule | Rules], Out, Keep_On) :- extract(Rule, In, Out1, KeepOn), ( KeepOn = false -> Out = Out1, Keep_On = KeepOn ; (KeepOn = stop -> Out = Out1, Keep_On = true ; apply_one_rule(Out1, Rules, Out, Keep_On))).   apply_one_rule(In, [], In, false) .     extract([Pattern, Replace], In, Out, Keep_On) :- ( Replace = [.|Rest] -> R = Rest ; R = Replace), ( (append(Pattern, End, T), append(Deb, T, In)) -> extract([Pattern, Replace], End, NewEnd, _Keep_On), append_3(Deb, R, NewEnd, Out), Keep_On = stop ; Out = In, ( R = Replace -> Keep_On = true ; Keep_On = false)).     append_3(A, B, C, D) :- append(A, B, T), append(T, C, D).   % creation of the rules markov(A) --> line(A).   line(A) --> text(A), newline.     newline --> ['\n'], newline. newline --> [].   text([]) --> comment([]). text(A) --> rule(A).   comment([]) --> ['#'], anything.   anything --> [X], {X \= '\n'}, anything. anything --> ['\n']. anything --> [].   rule([A,B]) --> pattern(A), whitespaces, ['-', '>'], whitespaces, end_rule(B).   pattern([X | R]) --> [X], {X \= '\n'}, pattern(R). pattern([]) --> [].   whitespaces --> ['\t'], whitespace. whitespaces --> [' '], whitespace.   whitespace --> whitespaces. whitespace --> [].   end_rule([.| A]) --> [.], rest_of_rule(A). end_rule(A) --> rest_of_rule(A). end_rule([]) --> [].   rest_of_rule(A) --> replacement(A).   replacement([X | R]) --> [X], {X \= '\n'}, replacement(R). replacement([]) --> [].  
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#Rust
Rust
#[derive(Debug)] enum U { U0(i32), U1(String), }   fn baz(i: u8) -> Result<(), U> { match i { 0 => Err(U::U0(42)), 1 => Err(U::U1("This will be returned from main".into())), _ => Ok(()), } }   fn bar(i: u8) -> Result<(), U> { baz(i) }   fn foo() -> Result<(), U> { for i in 0..2 { match bar(i) { Ok(()) => {}, Err(U::U0(n)) => eprintln!("Caught U0 in foo: {}", n), Err(e) => return Err(e), } } Ok(()) }   fn main() -> Result<(), U> { foo() }
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#Scala
Scala
object ExceptionsTest extends App { class U0 extends Exception class U1 extends Exception   def foo { for (i <- 0 to 1) try { bar(i) } catch { case e: U0 => println("Function foo caught exception U0") } }   def bar(i: Int) { def baz(i: Int) = { if (i == 0) throw new U0 else throw new U1 }   baz(i) // Nest those calls }   foo }  
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
#Maple
Maple
  errorproc:=proc(n) local a; try a:=1/n; catch "numeric exception: division by zero": error "Something went wrong when dividing." end try; end proc;  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
f[x_] := If[x > 10, Throw[overflow], x!]   Example usage : Catch[f[2] + f[11]] -> overflow   Catch[f[2] + f[3]] -> 8
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
#HolyC
HolyC
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
#Icon_and_Unicon
Icon and Unicon
procedure main()   write("Trying command ",cmd := if &features == "UNIX" then "ls" else "dir") system(cmd)   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
#IDL
IDL
$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
#Axe
Axe
Lbl FACT 1→R For(I,1,r₁) R*I→R End R Return
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
#Oforth
Oforth
: powint(r, n) | i | 1 n abs loop: i [ r * ] n isNegative ifTrue: [ inv ] ;   2 3 powint println 2 powint(3) println 1.2 4 powint println 1.2 powint(4) println
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
#PARI.2FGP
PARI/GP
ex(a, b)={ my(c = 1); while(b > 1, if(b % 2, c *= a); a = a^2; b >>= 1 ); a * c };
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#TXR
TXR
(defmacro if2 (cond1 cond2 both first second . neither) (let ((res1 (gensym)) (res2 (gensym))) ^(let ((,res1 ,cond1) (,res2 ,cond2)) (cond ((and ,res1 ,res2) ,both) (,res1 ,first) (,res2 ,second) (t ,*neither)))))