task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Clojure
Clojure
(.. Runtime getRuntime (exec "cmd /C dir"))
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#AntLang
AntLang
factorial:{1 */ 1+range[x]} /Call: factorial[1000]
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
#Icon_and_Unicon
Icon and Unicon
procedure main() bases := [5,5.] numbers := [0,2,2.,-1,3] every write("expon(",b := !bases,", ",x := !numbers,")=",(expon(b,x) | "failed") \ 1) end   procedure expon(base,power) local op,res   base := numeric(base) | runerror(102,base) power := power = integer(power) | runerr(101,power)   if power = 0 then return 1 else op := if power < 1 then (base := real(base)) & "/" # force real base else "*"   res := 1 every 1 to abs(power) do res := op(res,base) return res end
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.
#Nim
Nim
import macros   proc newIfElse(c, t, e: NimNode): NimNode {.compiletime.} = result = newIfStmt((c, t)) result.add(newNimNode(nnkElse).add(e))   macro if2(x, y: bool; z: untyped): untyped = var parts: array[4, NimNode] for i in parts.low .. parts.high: parts[i] = newNimNode(nnkDiscardStmt).add(NimNode(nil))   assert z.kind == nnkStmtList assert z.len <= 4   for i in 0 ..< z.len: assert z[i].kind == nnkCall assert z[i].len == 2   var j = 0   case $z[i][0] of "then": j = 0 of "else1": j = 1 of "else2": j = 2 of "else3": j = 3 else: assert false   parts[j] = z[i][1].last   result = newIfElse(x, newIfElse(y, parts[0], parts[1]), newIfElse(y, parts[2], parts[3]))   if2 2 > 1, 3 < 2: then: echo "1" else1: echo "2" else2: echo "3" else3: echo "4"   # Missing cases are supported: if2 2 > 1, 3 < 2: then: echo "1" else2: echo "3" else3: echo "4"   # Order can be swapped: if2 2 > 1, 3 < 2: then: echo "1" else2: echo "3" else1: echo "2" else3: echo "4"
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.
#OCaml
OCaml
(* Languages with pattern matching ALREADY HAVE THIS! *)   let myfunc pred1 pred2 = match (pred1, pred2) with | (true, true) -> print_endline ("(true, true)"); | (true, false) -> print_endline ("(true, false)"); | (false, true) -> print_endline ("(false, true)"); | (false, false) -> print_endline ("(false, false)");;   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
#Ruby
Ruby
1.upto(100) do |n| print "Fizz" if a = (n % 3).zero? print "Buzz" if b = (n % 5).zero? print n unless (a || b) puts end
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.
#Pascal
Pascal
http://www.primos.mat.br/Ate100G.html -> 75. de 16639648367 a 16875026921 76. de 16875026963 a 17110593779 77. de 17110593791 a 17346308407 ... my unit: 750000000 16875026921 760000000 17110593779 770000000 17346251243 <----Wrong
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.
#AppleScript
AppleScript
  set codeString to text returned of (display dialog "Enter BF code:" buttons "OK" default answer "") set inputString to text returned of (display dialog "Enter input string" buttons "OK" default answer "") set codePointer to 1 set loopPosns to {} set tape to {} set tapePointer to 1 set output to {} set inputPointer to 1 set step to 0   set thePath to (path to desktop as Unicode text) & "log.txt" set debug to (open for access file thePath with write permission)   write (step as string) & " (" & ((codePointer - 1) as string) & "): (The program contains " & ((length of codeString) as string) & " instructions.) " to debug   set step to 1   on betterMod(x, y) -- so -2 mod 256 is 254 instead of -2 local x local y try return -y * (round (x / y) rounding down) + x on error eMsg number eNum error "Can't call betterMod() on " & eMsg number eNum end try end betterMod   repeat while codePointer ≤ length of codeString set theChar to (get character codePointer of codeString)   if (theChar = "+") then repeat while (length of tape < tapePointer) set tape to tape & 0 end repeat set item tapePointer of tape to betterMod(((get item tapePointer of tape) + 1), 256) write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | a[" & ((tapePointer - 1) as string) & "]= " & ((item tapePointer of tape) as string) & " " to debug else if (theChar = "-") then repeat while (length of tape < tapePointer) set tape to tape & 0 end repeat set item tapePointer of tape to betterMod(((get item tapePointer of tape) - 1), 256) write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | a[" & ((tapePointer - 1) as string) & "]= " & ((item tapePointer of tape) as string) & " " to debug else if (theChar = "<") then set tapePointer to tapePointer - 1 write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | array pos. now " & ((tapePointer - 1) as string) & " " to debug   else if (theChar = ">") then set tapePointer to tapePointer + 1 write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | array pos. now " & ((tapePointer - 1) as string) & " " to debug   else if (theChar = "[") then repeat while (length of tape < tapePointer) set tape to tape & 0 end repeat write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | Array[" & ((tapePointer - 1) as string) & "] is '" & ((item tapePointer of tape) as string) & "'" to debug if (item tapePointer of tape ≠ 0) then set loopPosns to loopPosns & codePointer write " ** Loop nesting level: " & (((length of loopPosns) - 1) as string) & ". " to debug else write " " & (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | Not entering a loop but skipping to instruction number " to debug set matchLoops to 1 repeat while matchLoops ≠ 0 set codePointer to codePointer + 1 if (item codePointer of codeString = "[") then set matchLoops to matchLoops + 1 else if (item codePointer of codeString = "]") then set matchLoops to matchLoops - 1 end if end repeat write ((codePointer - 1) as string) & " " to debug end if   else if (theChar = "]") then repeat while (length of tape < tapePointer) set tape to tape & 0 end repeat write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | Array[" & ((tapePointer - 1) as string) & "] is '" & ((item tapePointer of tape) as string) & "' " to debug if (item tapePointer of tape ≠ 0) then write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | looping back to " & (((item (length of loopPosns) of loopPosns) - 1) as string) & " " to debug set codePointer to (item (length of loopPosns) of loopPosns) - 1 end if if (length of loopPosns > 1) then set loopPosns to items 1 thru ((length of loopPosns) - 1) of loopPosns else set loopPosns to {} end if   else if (theChar = ".") then repeat while (length of tape < tapePointer) set tape to tape & 0 end repeat write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | output '" & ((item tapePointer of tape) as string) & "' " & string id (item tapePointer of tape) & " " to debug set output to output & item tapePointer of tape   else if (theChar = ",") then repeat while (length of tape < tapePointer) set tape to tape & 0 end repeat if (inputPointer > length of inputString) then set inputPointer to 1 end if set item tapePointer of tape to id of item inputPointer of inputString set inputPointer to inputPointer + 1 write (step as string) & " (" & ((codePointer - 1) as string) & "): " & (item codePointer of codeString) & " | read in " & string id (item tapePointer of tape) & " (" & ((item tapePointer of tape) as string) & ") " to debug end if   set codePointer to codePointer + 1 set step to step + 1 end repeat   set strout to string id output display dialog strout close access debug  
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.
#APL
APL
evolve←{ ⍺←0.1 target←'METHINKS IT IS LIKE A WEASEL' charset←27↑⎕A fitness←{target+.=⍵} mutate←⍺∘{ (⍺>?(⍴target)/0){ ⍺:(?⍴charset)⊃charset ⍵ }¨⍵ } ⍵{ target≡⎕←⍵:⍵ next←mutate¨⍺/⊂⍵ ⍺∇(⊃⍒fitness¨next)⊃next }charset[?(⍴target)/⍴charset] }  
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
#Kabap
Kabap
  // Calculate the $n'th Fibonacci number   // Set this to how many in the sequence to generate $n = 10;   // These are what hold the current calculation $a = 0; $b = 1;   // This holds the complete sequence that is generated $sequence = "";   // Prepare a loop $i = 0; :calcnextnumber; $i = $i++;   // Do the calculation for this loop iteration $b = $a + $b; $a = $b - $a;   // Add the result to the sequence $sequence = $sequence << $a;   // Make the loop run a fixed number of times if $i < $n; { $sequence = $sequence << ", "; goto calcnextnumber; }   // Use the loop counter as the placeholder $i--;   // Return the sequence return = "Fibonacci number " << $i << " is " << $a << " (" << $sequence << ")";  
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Standard_ML
Standard ML
fun printIntList ls = ( List.app (fn n => print(Int.toString n ^ " ")) ls; print "\n" );   fun factors n = let fun factors'(n, k) = if k > n then [] else if n mod k = 0 then k :: factors'(n, k+1) else factors'(n, k+1) in factors'(n,1) end;  
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Swift
Swift
func factors(n: Int) -> [Int] {   return filter(1...n) { n % $0 == 0 } }
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Java
Java
function hq9plus(code) { var out = ''; var acc = 0;   for (var i=0; i<code.length; i++) { switch (code.charAt(i)) { case 'H': out += "hello, world\n"; break; case 'Q': out += code + "\n"; break; case '9': for (var j=99; j>1; j--) { out += j + " bottles of beer on the wall, " + j + " bottles of beer.\n"; out += "Take one down and pass it around, " + (j-1) + " bottles of beer.\n\n"; } out += "1 bottle of beer on the wall, 1 bottle of beer.\n" + "Take one down and pass it around, no more bottles of beer on the wall.\n\n" + "No more bottles of beer on the wall, no more bottles of beer.\n" + "Go to the store and buy some more, 99 bottles of beer on the wall.\n"; break; case '+': acc++; break; } } return out; }
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
#Groovy
Groovy
def markovInterpreterFor = { rules -> def ruleMap = [:] rules.eachLine { line -> (line =~ /\s*(.+)\s->\s([.]?)(.+)\s*/).each { text, key, terminating, value -> if (key.startsWith('#')) { return } ruleMap[key] = [text: value, terminating: terminating] } } [interpret: { text -> def originalText = '' while (originalText != text) { originalText = text for (Map.Entry e : ruleMap.entrySet()) { if (text.indexOf(e.key) >= 0) { text = text.replace(e.key, e.value.text) if (e.value.terminating) { return text } break } } } text }] }
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.
#Haskell
Haskell
import Control.Monad.Error import Control.Monad.Trans (lift)   -- Our "user-defined exception" tpe data MyError = U0 | U1 | Other deriving (Eq, Read, Show)   -- Required for any error type instance Error MyError where noMsg = Other strMsg _ = Other   -- Throwing and catching exceptions implies that we are working in a monad. In -- this case, we use ErrorT to support our user-defined exceptions, wrapping -- IO to be able to report the happenings. ('lift' converts ErrorT e IO a -- actions into IO a actions.)   foo = do lift (putStrLn "foo") mapM_ (\toThrow -> bar toThrow -- the protected call `catchError` \caught -> -- the catch operation -- ↓ what to do with it case caught of U0 -> lift (putStrLn "foo caught U0") _ -> throwError caught) [U0, U1] -- the two exceptions to throw     bar toThrow = do lift (putStrLn " bar") baz toThrow   baz toThrow = do lift (putStrLn " baz") throwError toThrow   -- We cannot use exceptions without at some outer level choosing what to do -- if an exception propagates all the way up. Here we just print the exception -- if there was one. main = do result <- runErrorT foo case result of Left e -> putStrLn ("Caught error at top level: " ++ show e) Right v -> putStrLn ("Return value: " ++ show v)
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.
#Icon_and_Unicon
Icon and Unicon
import Exceptions   class U0 : Exception() method getMessage() return "U0: " || (\message | "unknown") end end   class U1 : Exception() method getMessage() return "U1: " || (\message | "unknown") end end   procedure main() # (Because Exceptions are not built into Unicon, uncaught # exceptions are ignored. This clause will catch any # exceptions not caught farther down in the code.) case Try().call{ foo() } of { Try().catch(): { ex := Try().getException() write(ex.getMessage(), ":\n", ex.getLocation()) } } end   procedure foo() every 1|2 do { case Try().call{ bar() } of { Try().catch("U0"): { ex := Try().getException() write(ex.getMessage(), ":\n", ex.getLocation()) } } } end   procedure bar() return baz() end   procedure baz() initial U0().throw("First exception") U1().throw("Second exception") 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
#E
E
def nameOf(arg :int) { if (arg == 43) { return "Bob" } else { throw("Who?") } }   def catching(arg) { try { return ["ok", nameOf(arg)] } catch exceptionObj { return ["notok", exceptionObj] } }
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
#Elena
Elena
class MyException : Exception { constructor new() <= new("MyException raised"); }
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
#CMake
CMake
execute_process(COMMAND 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
#COBOL
COBOL
CALL "SYSTEM" USING BY CONTENT "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
#Apex
Apex
public static long fact(final Integer n) { if (n < 0) { System.debug('No negative numbers'); return 0; } long ans = 1; for (Integer i = 1; i <= n; i++) { ans *= i; } return ans; }
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
#J
J
exp =: */@:#~   10 exp 3 1000   10 exp 0 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
#Java
Java
public class Exp{ public static void main(String[] args){ System.out.println(pow(2,30)); System.out.println(pow(2.0,30)); //tests System.out.println(pow(2.0,-2)); }   public static double pow(double base, int exp){ if(exp < 0) return 1 / pow(base, -exp); double ans = 1.0; for(;exp > 0;--exp) ans *= base; 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.
#PARI.2FGP
PARI/GP
if2(c1,c2,tt,tf,ft,ff)={ if(c1, if(c2,tt,tf) , if(c2,ft,ff) ) };
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.
#Perl
Perl
  #!/usr/bin/perl use warnings; use strict; use v5.10;   =for starters   Syntax:   if2 condition1, condition2, then2 { # both conditions are true } else1 { # only condition1 is true } else2 { # only condition2 is true } orelse { # neither condition is true };   Any (but not all) of the `then' and `else' clauses can be omitted, and else1 and else2 can be specified in either order.   This extension is imperfect in several ways: * A normal if-statement uses round brackets, but this syntax forbids them. * Perl doesn't have a `then' keyword; if it did, it probably wouldn't be preceded by a comma. * Unless it's the last thing in a block, the whole structure must be followed by a semicolon. * Error messages appear at runtime, not compile time, and they don't show the line where the user's syntax error occurred.   We could solve most of these problems with a source filter, but those are dangerous. Can anyone else do better? Feel free to improve or replace.   =cut   # All the new `keywords' are in fact functions. Most of them return lists # of four closures, one of which is then executed by if2. Here are indexes into # these lists:   use constant { IdxThen => 0, IdxElse1 => 1, IdxElse2 => 2, IdxOrElse => 3 };   # Most of the magic is in the (&) prototype, which lets a function accept a # closure marked by nothing except braces.   sub orelse(&) { my $clause = shift; return undef, undef, undef, $clause; }   sub else2(&@) { my $clause = shift; die "Can't have two `else2' clauses" if defined $_[IdxElse2];   return (undef, $_[IdxElse1], $clause, $_[IdxOrElse]); }   sub else1(&@) { my $clause = shift; die "Can't have two `else1' clauses" if defined $_[IdxElse1];   return (undef, $clause, $_[IdxElse2], $_[IdxOrElse]); }   sub then2(&@) { die "Can't have two `then2' clauses" if defined $_[1+IdxThen];   splice @_, 1+IdxThen, 1; return @_; }   # Here, we collect the two conditions and four closures (some of which will be # undefined if some clauses are missing). We work out which of the four # clauses (closures) to call, and call it if it exists.   use constant { # Defining True and False is almost always bad practice, but here we # have a valid reason. True => (0 == 0), False => (0 == 1) };   sub if2($$@) { my $cond1 = !!shift; # Convert to Boolean to guarantee matching my $cond2 = !!shift; # against either True or False   die "if2 must be followed by then2, else1, else2, &/or orelse" if @_ != 4 or grep {defined and ref $_ ne 'CODE'} @_;   my $index; if (!$cond1 && !$cond2) {$index = IdxOrElse} if (!$cond1 && $cond2) {$index = IdxElse2 } if ( $cond1 && !$cond2) {$index = IdxElse1 } if ( $cond1 && $cond2) {$index = IdxThen }   my $closure = $_[$index]; &$closure if defined $closure; }   # This is test code. You can play with it by deleting up to three of the # four clauses.   sub test_bits($) { (my $n) = @_;   print "Testing $n: ";   if2 $n & 1, $n & 2, then2 { say "Both bits 0 and 1 are set"; } else1 { say "Only bit 0 is set"; } else2 { say "Only bit 1 is set"; } orelse { say "Neither bit is set"; } }   test_bits $_ for 0 .. 7;  
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
#Ruby_with_RSpec
Ruby with RSpec
  require 'fizzbuzz'   describe 'FizzBuzz' do context 'knows that a number is divisible by' do it '3' do expect(is_divisible_by_three?(3)).to be_true end it '5' do expect(is_divisible_by_five?(5)).to be_true end it '15' do expect(is_divisible_by_fifteen?(15)).to be_true end end context 'knows that a number is not divisible by' do it '3' do expect(is_divisible_by_three?(1)).not_to be_true end it '5' do expect(is_divisible_by_five?(1)).not_to be_true end it '15' do expect(is_divisible_by_fifteen?(1)).not_to be_true end end context 'while playing the game it returns' do it 'the number' do expect(fizzbuzz(1)).to eq 1 end it 'Fizz' do expect(fizzbuzz(3)).to eq 'Fizz' end it 'Buzz' do expect(fizzbuzz(5)).to eq 'Buzz' end it 'FizzBuzz' do expect(fizzbuzz(15)).to eq 'FizzBuzz' end end end  
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.
#Perl
Perl
use Math::Prime::Util qw(nth_prime prime_count primes); # Direct solutions. # primes([start],end) returns an array reference with all primes in the range # prime_count([start],end) uses sieving or LMO to return fast prime counts # nth_prime(n) does just that. It runs quite fast for native size inputs. say "First 20: ", join(" ", @{primes(nth_prime(20))}); say "Between 100 and 150: ", join(" ", @{primes(100,150)}); say prime_count(7700,8000), " primes between 7700 and 8000"; say "${_}th prime: ", nth_prime($_) for map { 10**$_ } 1..8;
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.
#Arturo
Arturo
; ; Brainf*ck compiler ; In Arturo ;   Tape: [0] DataPointer: new 0 InstructionPointer: new 0   ; Look for jumps in Code an register them ; in the Jumps table   precomputeJumps: function [][ vstack: new [] jumphash: new #[] instrPointer: 0   while [instrPointer<CodeLength] [ command: get split Code instrPointer if? command="[" -> 'vstack ++ instrPointer else [ if command="]" [ target: last vstack chop 'vstack jumphash\[target]: instrPointer jumphash\[instrPointer]: target ] ] instrPointer: instrPointer+1 ] jumphash ]   ; Check if current state is valid   StateIsValid: function [][ all? @[ 0 =< DataPointer DataPointer < size Tape 0 =< InstructionPointer InstructionPointer < CodeLength ] ]   ; Compile the program   interpret: function [].export:[DataPointer,InstructionPointer,Tape][ while [StateIsValid][ command: get split Code InstructionPointer case [command=] when? ["+"] -> Tape\[DataPointer]: Tape\[DataPointer]+1 when? ["-"] -> Tape\[DataPointer]: Tape\[DataPointer]-1 when? [">"] [ inc 'DataPointer if DataPointer = size Tape -> Tape: Tape ++ 0 ] when? ["<"] -> dec 'DataPointer when? ["."] -> prints to :string to :char Tape\[DataPointer] when? [","][ inp: to :integer input "" if inp=13 -> inp: 10 if inp=3 -> panic "something went wrong!" set Tape DataPointer inp ] when? ["["] -> if 0 = get Tape DataPointer [ InstructionPointer: new get Jumps InstructionPointer ]   when? ["]"] -> if 0 <> get Tape DataPointer [ InstructionPointer: new get Jumps InstructionPointer ]   inc 'InstructionPointer ] ]   Code: "" if? 1>size arg -> Code: "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." else -> Code: read arg\0   CodeLength: size Code Jumps: precomputeJumps   interpret
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.
#AutoHotkey
AutoHotkey
output := "" target := "METHINKS IT IS LIKE A WEASEL" targetLen := StrLen(target) Loop, 26 possibilities_%A_Index% := Chr(A_Index+64) ; A-Z possibilities_27 := " " C := 100   parent := "" Loop, %targetLen% { Random, randomNum, 1, 27 parent .= possibilities_%randomNum% }   Loop, { If (target = parent) Break If (Mod(A_Index,10) = 0) output .= A_Index ": " parent ", fitness: " fitness(parent, target) "`n" bestFit := 0 Loop, %C% If ((fitness := fitness(spawn := mutate(parent), target)) > bestFit) bestSpawn := spawn , bestFit := fitness parent := bestFit > fitness(parent, target) ? bestSpawn : parent iter := A_Index } output .= parent ", " iter MsgBox, % output ExitApp   mutate(parent) { local output, replaceChar, newChar output := "" Loop, %targetLen% { Random, replaceChar, 0, 9 If (replaceChar != 0) output .= SubStr(parent, A_Index, 1) else { Random, newChar, 1, 27 output .= possibilities_%newChar% } } Return output }   fitness(string, target) { totalFit := 0 Loop, % StrLen(string) If (SubStr(string, A_Index, 1) = SubStr(target, A_Index, 1)) totalFit++ Return totalFit }
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
#Klingphix
Klingphix
:Fibonacci dup 0 less ( ["Invalid argument"] [1 1 rot 2 sub [drop over over add] for] ) if ;   30 Fibonacci pstack print nl   msec print nl "bertlham " input
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Tailspin
Tailspin
  [1..351 -> \(when <?(351 mod $ <=0>)> do $! \)] -> !OUT::write  
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Tcl
Tcl
proc factors {n} { set factors {} for {set i 1} {$i <= sqrt($n)} {incr i} { if {$n % $i == 0} { lappend factors $i [expr {$n / $i}] } } return [lsort -unique -integer $factors] } puts [factors 64] puts [factors 45] puts [factors 53]
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#JavaScript
JavaScript
function hq9plus(code) { var out = ''; var acc = 0;   for (var i=0; i<code.length; i++) { switch (code.charAt(i)) { case 'H': out += "hello, world\n"; break; case 'Q': out += code + "\n"; break; case '9': for (var j=99; j>1; j--) { out += j + " bottles of beer on the wall, " + j + " bottles of beer.\n"; out += "Take one down and pass it around, " + (j-1) + " bottles of beer.\n\n"; } out += "1 bottle of beer on the wall, 1 bottle of beer.\n" + "Take one down and pass it around, no more bottles of beer on the wall.\n\n" + "No more bottles of beer on the wall, no more bottles of beer.\n" + "Go to the store and buy some more, 99 bottles of beer on the wall.\n"; break; case '+': acc++; break; } } return out; }
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
#Haskell
Haskell
import Data.List (isPrefixOf) import Data.Maybe (catMaybes) import Control.Monad import Text.ParserCombinators.Parsec import System.IO import System.Environment (getArgs)   main = do args <- getArgs unless (length args == 1) $ fail "Please provide exactly one source file as an argument." let sourcePath = head args source <- readFile sourcePath input <- getContents case parse markovParser sourcePath source of Right rules -> putStr $ runMarkov rules input Left err -> hPutStrLn stderr $ "Parse error at " ++ show err   data Rule = Rule {from :: String, terminating :: Bool, to :: String}   markovParser :: Parser [Rule] markovParser = liftM catMaybes $ (comment <|> rule) `sepEndBy` many1 newline where comment = char '#' >> skipMany nonnl >> return Nothing rule = liftM Just $ liftM3 Rule (manyTill (nonnl <?> "pattern character") $ try arrow) (succeeds $ char '.') (many nonnl) arrow = ws >> string "->" >> ws <?> "whitespace-delimited arrow" nonnl = noneOf "\n" ws = many1 $ oneOf " \t" succeeds p = option False $ p >> return True   runMarkov :: [Rule] -> String -> String runMarkov rules s = f rules s where f [] s = s f (Rule from terminating to : rs) s = g "" s where g _ "" = f rs s g before ahead@(a : as) = if from `isPrefixOf` ahead then let new = reverse before ++ to ++ drop (length from) ahead in if terminating then new else f rules new else g (a : before) as
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.
#Io
Io
U0 := Exception clone U1 := Exception clone   foo := method( for(i,1,2, try( bar(i) )catch( U0, "foo caught U0" print )pass ) ) bar := method(n, baz(n) ) baz := method(n, if(n == 1,U0,U1) raise("baz with n = #{n}" interpolate) )   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.
#J
J
main=: monad define smoutput 'main' try. foo '' catcht. smoutput 'main caught ',type_jthrow_ end. )   foo=: monad define smoutput ' foo' for_i. 0 1 do. try. bar i catcht. if. type_jthrow_-:'U0' do. smoutput ' foo caught ',type_jthrow_ else. throw. end. end. end. )   bar=: baz [ smoutput bind ' bar'   baz=: monad define smoutput ' baz' type_jthrow_=: 'U',":y throw. )
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
#Erlang
Erlang
  -module( exceptions ).   -export( [task/0] ).   task() -> try erlang:throw( new_exception )   catch _:Exception -> io:fwrite( "Catched ~p~n", [Exception] )   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
#Factor
Factor
"Install Linux, Problem Solved" throw   TUPLE: velociraptor ; \ velociraptor new throw
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
#CoffeeScript
CoffeeScript
  { spawn } = require 'child_process'   ls = spawn 'ls'   ls.stdout.on 'data', ( data ) -> console.log "Output: #{ data }"   ls.stderr.on 'data', ( data ) -> console.error "Error: #{ data }"   ls.on 'close', -> console.log "'ls' has finished executing."  
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
#Common_Lisp
Common Lisp
(with-output-to-string (stream) (extensions:run-program "ls" nil :output stream))
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
#APL
APL
 !6 720
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
#JavaScript
JavaScript
function pow(base, exp) { if (exp != Math.floor(exp)) throw "exponent must be an integer"; if (exp < 0) return 1 / pow(base, -exp); var ans = 1; while (exp > 0) { ans *= base; exp--; } return ans; }
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
#jq
jq
# 0^0 => 1 # NOTE: jq converts very large integers to floats. # This implementation uses reduce to avoid deep recursion def power_int(n): if n == 0 then 1 elif . == 0 then 0 elif n < 0 then 1/power_int(-n) elif ((n | floor) == n) then ( (n % 2) | if . == 0 then 1 else -1 end ) as $sign | if (. == -1) then $sign elif . < 0 then (( -(.) | power_int(n) ) * $sign) else . as $in | reduce range(1;n) as $i ($in; . * $in) end else error("This is a toy implementation that requires n be integral") end ;
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.
#Phix
Phix
switch {condition1,condition2} do case {true,true}: case {true,false}: case {false,true}: case {false,false}: end switch
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.
#PHL
PHL
module stmts;   import phl::lang::io;   /* LinkedList --> Each element contains a condition */ struct @ConditionalChain { field @Boolean cond; field @ConditionalChain next;   @ConditionalChain init(@Boolean cond, @ConditionalChain next) [ this::cond = cond; this::next = next;   return this; ]   /* * If the condition is true executes the closure and returns a false element, otherwise returns the next condition * * Execution starts from the first element, and iterates until the right element is found. */ @ConditionalChain then(@Closure<@Void> closure) [ if (isNull(next())) return new @ConditionalChain.init(false, null); if (cond()) { closure(); return new @ConditionalChain.init(false, null); } else return next(); ]   /* Operators create a cool look */ @ConditionalChain operator then(@Closure<@Void> closure) alias @ConditionalChain.then; @ConditionalChain operator else1(@Closure<@Void> closure) alias @ConditionalChain.then; @ConditionalChain operator else2(@Closure<@Void> closure) alias @ConditionalChain.then; @ConditionalChain operator orElse(@Closure<@Void> closure) alias @ConditionalChain.then; };   /* Returns linked list [a && b, a, b, true] */ @ConditionalChain if2(@Boolean a, @Boolean b) [ return new @ConditionalChain.init(a && b, new @ConditionalChain.init(a, new @ConditionalChain.init(b, new @ConditionalChain.init(true, null)))); ]   @Void main [ if2(false, true) then [ println("Not this!"); ] else1 [ println("Not this!"); ] else2 [ println("This!"); ] orElse [ println("Not this!"); ]; ]
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
#Run_BASIC
Run BASIC
fn main() { for i in 1..=100 { match (i % 3, i % 5) { (0, 0) => println!("fizzbuzz"), (0, _) => println!("fizz"), (_, 0) => println!("buzz"), (_, _) => println!("{}", i), } } }
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.
#Phix
Phix
with javascript_semantics if platform()!=JS then free_console() end if sequence primes = {2,3,5,7} atom sieved = 10 procedure add_block() integer N = min((sieved-1)*sieved,400000) sequence sieve = repeat(1,N) -- sieve[i] is really i+sieved for i=2 to length(primes) do -- (evens filtered on output) atom p = primes[i], p2 = p*p if p2>sieved+N then exit end if if p2<sieved+1 then p2 += ceil((sieved+1-p2)/p)*p end if p2 -= sieved if and_bits(p2,1)=0 then p2 += p end if -- if sieve[p2] then -- dang! for k=p2 to N by p*2 do sieve[k] = 0 end for -- end if end for for i=1 to N by 2 do if sieve[i] then primes &= i+sieved end if end for sieved += N end procedure function is_prime2(integer n) while sieved<n do add_block() end while return binary_search(n,primes)>0 end function atom t0 = time() while length(primes)<20 do add_block() end while printf(1,"The first 20 primes are: ") ?primes[1..20] while sieved<150 do add_block() end while sequence s = {} for k=abs(binary_search(100,primes)) to length(primes) do integer p = primes[k] if p>150 then exit end if s &= p end for printf(1,"The primes between 100 and 150 are: ") ?s s = {} for i=7700 to 8000 do if is_prime2(i) then s&=i end if end for printf(1,"There are %d primes between 7700 and 8000.\n",length(s)) for i=1 to iff(platform()=JS?7:8) do integer k = power(10,i) while length(primes)<k do add_block() end while printf(1,"The %,dth prime is : %d\n",{k,primes[k]}) end for ?time()-t0 if platform()!=JS then {} = wait_key() end if
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.
#AutoHotkey
AutoHotkey
; AutoFucck ; A AutoIt Brainfuck Interpreter ; by minx ; AutoIt Version: 3.3.8.x   ; Commands: ; - DEC ; + INC ; [ LOOP START ; ] LOOP END ; . Output cell value as ASCII Chr ; , Input a ASCII char (cell value = ASCII code) ; : Ouput cell value as integer ; ; Input a Integer ; _ Output a single whitespace ; / Output an Carriage Return and Line Feed   ; You can load & save .atf Files.   #include <WindowsConstants.au3> #include <EditConstants.au3> #include <Array.au3> #include <GUIConstants.au3> #include <StaticCOnstants.au3>   HotKeySet("{F5}", "_Runn")   $hMain = GUICreate("Autofuck - Real Brainfuck Interpreter", 600, 525) $mMain = GUICtrlCreateMenu("File") Global $mCode = GUICtrlCreateMenu("Code") $mInfo = GUICtrlCreateMenu("Info") $mCredits = GUICtrlCreateMenuItem("Credits", $mInfo) $mFile_New = GUICtrlCreateMenuItem("New", $mMain) $mFile_Open = GUICtrlCreateMenuItem("Open", $mMain) $mFile_Save = GUICtrlCreateMenuItem("Save", $mMain) Global $mCode_Run = GUICtrlCreateMenuItem("Run [F5]", $mCode) Global $lStatus = GUICtrlCreateLabel("++ Autofuck started...", 5, 480, 590, 20, $SS_SUNKEN) GUICtrlSetFont(-1, Default, Default, Default, "Courier New") $eCode = GUICtrlCreateEdit("", 5, 5, 590, 350) GUICtrlSetFont(-1, Default, Default, Default, "Courier New") $eConsole = GUICtrlCreateEdit("", 5, 360, 590, 115, $ES_WANTRETURN) GUICtrlSetFont(-1, Default, Default, Default, "Courier New") GUISetState()   While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $mFile_New GUICtrlSetData($eCode, "") Case $mFile_Open GUICtrlSetData($eCode, FileRead(FileOpenDialog("Open Autofuck script", @DesktopDir, "Autofuck (*.atf)"))) Case $mFile_Save FileWrite(FileOpen(StringReplace(FileSaveDialog("Save Autofuck script", @DesktopDir, "Autofuck (*.atf)"), ".atf", "") &".atf", 2), GUICtrlRead($eCode)) Case $GUI_EVENT_CLOSE Exit Case $mCredits MsgBox(0, "Autofuck", "Copyright by: "&@CRLF&"minx (autoit.de)"&@CRLF&"crashdemons (autoitscript.com)") EndSwitch WEnd   Func _Runn() $Timer = TimerInit() GUICtrlSetData($lStatus, "++ Program started") Global $tData=DllStructCreate('BYTE[65536]') Global $pData=0 GUICtrlSetData($eConsole, "") Local $aError[6]=['','Unmatched closing bracket during search','Unmatched opening bracket during search','Unexpected closing bracket','Data pointer passed left boundary','Data pointer passed right boundary'] Local $sError='' Local $i=_Run(GUICtrlRead($eCode)) If @error>=0 And @error<6 Then $sError=$aError[@error] If StringLen($sError) Then GUICtrlSetData($eConsole, 'ERROR: '&$sError&'.'&@CRLF&'Ending Instruction Pointer: '&($i-1)&@CRLF&'Current Data Pointer: '&$pData) GUICtrlSetData($lStatus, "++ Program terminated. Runtime: "& Round( TimerDiff($Timer) / 1000, 4) &"s") EndFunc   Func _Run($Code,$iStart=1,$iEnd=0) If $iEnd<1 Then $iEnd=StringLen($Code) For $i = $iStart to $iEnd Switch StringMid($Code, $i, 1) Case ">" $pData+=1 If $pData=65536 Then Return SetError(5,0,$i) Case "<" $pData-=1 If $pData<0 Then Return SetError(4,0,$i) Case "+" DllStructSetData($tData,1,DllStructGetData($tData,1,$pData+1)+1,$pData+1) Case "-" DllStructSetData($tData,1,DllStructGetData($tData,1,$pData+1)-1,$pData+1) Case ":" GUICtrlSetData($eConsole, GUICtrlRead($eConsole) & (DllStructGetData($tData,1,$pData+1))) Case "." GUICtrlSetData($eConsole, GUICtrlRead($eConsole) & Chr(DllStructGetData($tData,1,$pData+1))) Case ";" Local $cIn=StringMid(InputBox('Autofuck','Enter Number'),1) DllStructSetData($tData,1,Number($cIn),$pData+1) Case "," Local $cIn=StringMid(InputBox('Autofuck','Enter one ASCII character'),1,1) DllStructSetData($tData,1,Asc($cIn),$pData+1) Case "[" Local $iStartSub=$i Local $iEndSub=_MatchBracket($Code,$i,$iEnd) If @error<>0 Then Return SetError(@error,0,$iEndSub) While DllStructGetData($tData,1,$pData+1)<>0 Local $iRet=_Run($Code,$iStartSub+1,$iEndSub-1) If @error<>0 Then Return SetError(@error,0,$iRet) WEnd $i=$iEndSub Case ']' Return SetError(3,0,$i) Case "_" GUICtrlSetData($eConsole, GUICtrlRead($eConsole)&" ") Case "/" GUICtrlSetData($eConsole, GUICtrlRead($eConsole)&@CRLF) EndSwitch Next Return 0 EndFunc   Func _MatchBracket($Code,$iStart=1,$iEnd=0) If $iEnd<1 Then $iEnd=StringLen($Code) Local $Open=0 For $i=$iStart To $iEnd Switch StringMid($Code,$i,1) Case '[' $Open+=1 Case ']' $Open-=1 If $Open=0 Then Return $i If $Open<0 Then Return SetError(1,0,$i) EndSwitch Next If $Open>0 Then Return SetError(2,0,$i) Return 0 EndFunc
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.
#AWK
AWK
  #!/bin/awk -f function randchar(){ return substr(charset,randint(length(charset)+1),1) } function mutate(gene,rate ,l,newgene){ newgene = "" for (l=1; l < 1+length(gene); l++){ if (rand() < rate) newgene = newgene randchar() else newgene = newgene substr(gene,l,1) } return newgene } function fitness(gene,target ,k,fit){ fit = 0 for (k=1;k<1+length(gene);k++){ if (substr(gene,k,1) == substr(target,k,1)) fit = fit + 1 } return fit } function randint(n){ return int(n * rand()) } function evolve(){ maxfit = fitness(parent,target) oldfit = maxfit maxj = 0 for (j=1; j < D; j++){ child[j] = mutate(parent,mutrate) fit[j] = fitness(child[j],target) if (fit[j] > maxfit) { maxfit = fit[j] maxj = j } } if (maxfit > oldfit) parent = child[maxj] }   BEGIN{ target = "METHINKS IT IS LIKE A WEASEL" charset = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" mutrate = 0.10 if (ARGC > 1) mutrate = ARGV[1] lenset = length(charset) C = 100 D = C + 1 parent = "" for (j=1; j < length(target)+1; j++) { parent = parent randchar() } print "target: " target print "fitness of target: " fitness(target,target) print "initial parent: " parent gens = 0 while (parent != target){ evolve() gens = gens + 1 if (gens % 10 == 0) print "after " gens " generations,","new parent: " parent," with fitness: " fitness(parent,target) } print "after " gens " generations,"," evolved parent: " 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
#Kotlin
Kotlin
enum class Fibonacci { ITERATIVE { override fun get(n: Int): Long = if (n < 2) { n.toLong() } else { var n1 = 0L var n2 = 1L repeat(n) { val sum = n1 + n2 n1 = n2 n2 = sum } n1 } }, RECURSIVE { override fun get(n: Int): Long = if (n < 2) n.toLong() else this[n - 1] + this[n - 2] }, CACHING { val cache: MutableMap<Int, Long> = mutableMapOf(0 to 0L, 1 to 1L) override fun get(n: Int): Long = if (n < 2) n.toLong() else impl(n) private fun impl(n: Int): Long = cache.computeIfAbsent(n) { impl(it-1) + impl(it-2) } },  ;   abstract operator fun get(n: Int): Long }   fun main() { val r = 0..30 for (fib in Fibonacci.values()) { print("${fib.name.padEnd(10)}:") for (i in r) { print(" " + fib[i]) } println() } }
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#UNIX_Shell
UNIX Shell
factor() { r=`echo "sqrt($1)" | bc` # or `echo $1 v p | dc` i=1 while [ $i -lt $r ]; do if [ `expr $1 % $i` -eq 0 ]; then echo $i expr $1 / $i fi i=`expr $i + 1` done | sort -nu }  
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Ursa
Ursa
decl int n set n (int args<1>)   decl int i for (set i 1) (< i (+ (/ n 2) 1)) (inc i) if (= (mod n i) 0) out i " " console end if end for out n endl console
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Julia
Julia
hello() = println("Hello, world!") quine() = println(src) bottles() = for i = 99:-1:1 print("\n$i bottles of beer on the wall\n$i bottles of beer\nTake one down, pass it around\n$(i-1) bottles of beer on the wall\n") end acc = 0 incr() = global acc += 1   const dispatch = Dict( 'h' => hello, 'q' => quine, '9' => bottles, '+' => incr)   if length(ARGS) < 1 println("Usage: julia ./HQ9+.jl file.hq9") exit(1) else file = ARGS[1] end   try open(file) do s global src = readstring(s) end catch warning("can't open $file") exit(1) end   for i in lowercase(src) if haskey(dispatch, i) dispatch[i]() end end
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Kotlin
Kotlin
// version 1.1.3   fun hq9plus(code: String) { var acc = 0 val sb = StringBuilder() for (c in code) { sb.append( when (c) { 'h', 'H' -> "Hello, world!\n" 'q', 'Q' -> code + "\n" '9'-> { val sb2 = StringBuilder() for (i in 99 downTo 1) { val s = if (i > 1) "s" else "" sb2.append("$i bottle$s of beer on the wall\n") sb2.append("$i bottle$s of beer\n") sb2.append("Take one down, pass it around\n") } sb2.append("No more bottles of beer on the wall!\n") sb2.toString() } '+' -> { acc++; "" } // yeah, it's weird! else -> throw IllegalArgumentException("Code contains illegal operation '$c'") } ) } println(sb) }   fun main(args: Array<String>) { val code = args[0] // pass in code as command line argument (using hq9+) hq9plus(code) }
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
#Icon_and_Unicon
Icon and Unicon
procedure main(A) rules := loadRules(open(A[1],"r")) every write(line := !&input, " -> ",apply(rules, line)) end   record rule(pat, term, rep)   procedure loadRules(f) rules := [] every !f ? if not ="#" then put(rules, rule(1(trim(tab(find("->"))),move(2),tab(many(' \t'))), (="."|&null), trim(tab(0)))) return rules end   procedure apply(rules, line) s := line repeat { s ?:= tab(find((r := !rules).pat)) || r.rep || (move(*r.pat),tab(0)) if (s == line) | \r.term then return s else line := s } end
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.
#Java
Java
class U0 extends Exception { } class U1 extends Exception { }   public class ExceptionsTest { public static void foo() throws U1 { for (int i = 0; i <= 1; i++) { try { bar(i); } catch (U0 e) { System.out.println("Function foo caught exception U0"); } } }   public static void bar(int i) throws U0, U1 { baz(i); // Nest those calls }   public static void baz(int i) throws U0, U1 { if (i == 0) throw new U0(); else throw new U1(); }   public static void main(String[] args) throws U1 { 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.
#JavaScript
JavaScript
function U() {} U.prototype.toString = function(){return this.className;}   function U0() { this.className = arguments.callee.name; } U0.prototype = new U();   function U1() { this.className = arguments.callee.name; } U1.prototype = new U();   function foo() { for (var i = 1; i <= 2; i++) { try { bar(); } catch(e if e instanceof U0) { print("caught exception " + e); } } }   function bar() { baz(); }   function baz() { // during the first call, redefine the function for subsequent calls baz = function() {throw(new U1());} throw(new U0()); }   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
#Fancy
Fancy
# define custom exception class # StandardError is base class for all exception classes class MyError : StandardError { def initialize: message { # forward to StdError's initialize method super initialize: message } }   try { # raises/throws a new MyError exception within try-block MyError new: "my message" . raise! } catch MyError => e { # catch exception # this will print "my message" e message println } finally { # this will always be executed (as in e.g. Java) "This is how exception handling in Fancy works :)" println }
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
#Fantom
Fantom
  // Create a new error class by subclassing sys::Err const class SpecialErr : Err { // you must provide some message about the error // to the parent class, for reporting new make () : super ("special error") {} }   class Main { static Void fn () { throw SpecialErr () }   public static Void main () { try fn() catch (SpecialErr e) echo ("Caught " + e) } }  
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
#D
D
  import std.process, std.stdio; //these two alternatives wait for the process to return, and capture the output //each process function returns a Tuple of (int)"status" and (string)"output auto ls_string = executeShell("ls -l"); //takes single string writeln((ls_string.status == 0) ? ls_string.output : "command failed");   auto ls_array = execute(["ls", "-l"]); //takes array of strings writeln((ls_array.status == 0) ? ls_array.output : "command failed"); //other alternatives exist to spawn processes in parallel and capture output via pipes  
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
#dc
dc
! 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
#AppleScript
AppleScript
on factorial(x) if x < 0 then return 0 set R to 1 repeat while x > 1 set {R, x} to {R * x, x - 1} end repeat return R end factorial
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
#Julia
Julia
  function pow(base::Number, exp::Integer) r = one(base) for i = 1:exp r *= base end return r end  
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
#Kotlin
Kotlin
// version 1.0.6   infix fun Int.ipow(exp: Int): Int = when { this == 1 -> 1 this == -1 -> if (exp and 1 == 0) 1 else -1 exp < 0 -> throw IllegalArgumentException("invalid exponent") exp == 0 -> 1 else -> { var ans = 1 var base = this var e = exp while (e > 1) { if (e and 1 == 1) ans *= base e = e shr 1 base *= base } ans * base } }   infix fun Double.dpow(exp: Int): Double { var ans = 1.0 var e = exp var base = if (e < 0) 1.0 / this else this if (e < 0) e = -e while (e > 0) { if (e and 1 == 1) ans *= base e = e shr 1 base *= base } return ans }   fun main(args: Array<String>) { println("2 ^ 3 = ${2 ipow 3}") println("1 ^ -10 = ${1 ipow -10}") println("-1 ^ -3 = ${-1 ipow -3}") println() println("2.0 ^ -3 = ${2.0 dpow -3}") println("1.5 ^ 0 = ${1.5 dpow 0}") println("4.5 ^ 2 = ${4.5 dpow 2}") }
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.
#PicoLisp
PicoLisp
(undef 'if2) # Undefine the built-in 'if2'   (de if2 "P" (if (eval (pop '"P")) (eval ((if (eval (car "P")) cadr caddr) "P")) (if (eval (car "P")) (eval (cadddr "P")) (run (cddddr "P")) ) ) )
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.
#Plain_TeX
Plain TeX
\def\iftwo#1#2#3#4#5\elsefirst#6\elsesecond#7\elseneither#8\owtfi {\if#1#2\if#3#4#5\else#6\fi\else\if#3#4#7\else#8\fi\fi}   \def\both{***both***} \def\first{***first***} \def\second{***second***} \def\neither{***neither***} \message{\iftwo{1}{1}{2}{2}\both\elsefirst\first\elsesecond\second\elseneither\neither\owtfi} \message{\iftwo{1}{1}{2}{-2}\both\elsefirst\first\elsesecond\second\elseneither\neither\owtfi} \message{\iftwo{1}{-1}{2}{2}\both\elsefirst\first\elsesecond\second\elseneither\neither\owtfi} \message{\iftwo{1}{-1}{2}{-2}\both\elsefirst\first\elsesecond\second\elseneither\neither\owtfi}   \bye
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
#Rust
Rust
fn main() { for i in 1..=100 { match (i % 3, i % 5) { (0, 0) => println!("fizzbuzz"), (0, _) => println!("fizz"), (_, 0) => println!("buzz"), (_, _) => println!("{}", i), } } }
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.
#PicoLisp
PicoLisp
(de prime? (N Lst) (let S (sqrt N) (for D Lst (T (> D S) T) (T (=0 (% N D)) NIL) ) ) ) (de primeseq (A B) (let (I 1 R) (nth (make (link 2) (while (> A (inc 'I 2)) (and (prime? I (made)) (link I)) ) (setq R (length (made))) (while (> B I) (and (prime? I (made)) (link I)) (inc 'I 2) ) ) (inc R) ) ) ) (de take (N) (let I 1 (make (link 2) (do (dec N) (until (prime? (inc 'I 2) (made))) (link I) ) ) ) )   (prin "First 20 primes: ") (println (take 20)) (prin "Primes between 100 and 150: ") (println (primeseq 100 150)) (prinl "Number of primes between 7700 and 8000: " (length (primeseq 7700 8000)) ) (for N (10 100 1000 10000 100000 1000000) (prinl N "th prime: " (last (take N)) ) )
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.
#AutoIt
AutoIt
; AutoFucck ; A AutoIt Brainfuck Interpreter ; by minx ; AutoIt Version: 3.3.8.x   ; Commands: ; - DEC ; + INC ; [ LOOP START ; ] LOOP END ; . Output cell value as ASCII Chr ; , Input a ASCII char (cell value = ASCII code) ; : Ouput cell value as integer ; ; Input a Integer ; _ Output a single whitespace ; / Output an Carriage Return and Line Feed   ; You can load & save .atf Files.   #include <WindowsConstants.au3> #include <EditConstants.au3> #include <Array.au3> #include <GUIConstants.au3> #include <StaticCOnstants.au3>   HotKeySet("{F5}", "_Runn")   $hMain = GUICreate("Autofuck - Real Brainfuck Interpreter", 600, 525) $mMain = GUICtrlCreateMenu("File") Global $mCode = GUICtrlCreateMenu("Code") $mInfo = GUICtrlCreateMenu("Info") $mCredits = GUICtrlCreateMenuItem("Credits", $mInfo) $mFile_New = GUICtrlCreateMenuItem("New", $mMain) $mFile_Open = GUICtrlCreateMenuItem("Open", $mMain) $mFile_Save = GUICtrlCreateMenuItem("Save", $mMain) Global $mCode_Run = GUICtrlCreateMenuItem("Run [F5]", $mCode) Global $lStatus = GUICtrlCreateLabel("++ Autofuck started...", 5, 480, 590, 20, $SS_SUNKEN) GUICtrlSetFont(-1, Default, Default, Default, "Courier New") $eCode = GUICtrlCreateEdit("", 5, 5, 590, 350) GUICtrlSetFont(-1, Default, Default, Default, "Courier New") $eConsole = GUICtrlCreateEdit("", 5, 360, 590, 115, $ES_WANTRETURN) GUICtrlSetFont(-1, Default, Default, Default, "Courier New") GUISetState()   While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $mFile_New GUICtrlSetData($eCode, "") Case $mFile_Open GUICtrlSetData($eCode, FileRead(FileOpenDialog("Open Autofuck script", @DesktopDir, "Autofuck (*.atf)"))) Case $mFile_Save FileWrite(FileOpen(StringReplace(FileSaveDialog("Save Autofuck script", @DesktopDir, "Autofuck (*.atf)"), ".atf", "") &".atf", 2), GUICtrlRead($eCode)) Case $GUI_EVENT_CLOSE Exit Case $mCredits MsgBox(0, "Autofuck", "Copyright by: "&@CRLF&"minx (autoit.de)"&@CRLF&"crashdemons (autoitscript.com)") EndSwitch WEnd   Func _Runn() $Timer = TimerInit() GUICtrlSetData($lStatus, "++ Program started") Global $tData=DllStructCreate('BYTE[65536]') Global $pData=0 GUICtrlSetData($eConsole, "") Local $aError[6]=['','Unmatched closing bracket during search','Unmatched opening bracket during search','Unexpected closing bracket','Data pointer passed left boundary','Data pointer passed right boundary'] Local $sError='' Local $i=_Run(GUICtrlRead($eCode)) If @error>=0 And @error<6 Then $sError=$aError[@error] If StringLen($sError) Then GUICtrlSetData($eConsole, 'ERROR: '&$sError&'.'&@CRLF&'Ending Instruction Pointer: '&($i-1)&@CRLF&'Current Data Pointer: '&$pData) GUICtrlSetData($lStatus, "++ Program terminated. Runtime: "& Round( TimerDiff($Timer) / 1000, 4) &"s") EndFunc   Func _Run($Code,$iStart=1,$iEnd=0) If $iEnd<1 Then $iEnd=StringLen($Code) For $i = $iStart to $iEnd Switch StringMid($Code, $i, 1) Case ">" $pData+=1 If $pData=65536 Then Return SetError(5,0,$i) Case "<" $pData-=1 If $pData<0 Then Return SetError(4,0,$i) Case "+" DllStructSetData($tData,1,DllStructGetData($tData,1,$pData+1)+1,$pData+1) Case "-" DllStructSetData($tData,1,DllStructGetData($tData,1,$pData+1)-1,$pData+1) Case ":" GUICtrlSetData($eConsole, GUICtrlRead($eConsole) & (DllStructGetData($tData,1,$pData+1))) Case "." GUICtrlSetData($eConsole, GUICtrlRead($eConsole) & Chr(DllStructGetData($tData,1,$pData+1))) Case ";" Local $cIn=StringMid(InputBox('Autofuck','Enter Number'),1) DllStructSetData($tData,1,Number($cIn),$pData+1) Case "," Local $cIn=StringMid(InputBox('Autofuck','Enter one ASCII character'),1,1) DllStructSetData($tData,1,Asc($cIn),$pData+1) Case "[" Local $iStartSub=$i Local $iEndSub=_MatchBracket($Code,$i,$iEnd) If @error<>0 Then Return SetError(@error,0,$iEndSub) While DllStructGetData($tData,1,$pData+1)<>0 Local $iRet=_Run($Code,$iStartSub+1,$iEndSub-1) If @error<>0 Then Return SetError(@error,0,$iRet) WEnd $i=$iEndSub Case ']' Return SetError(3,0,$i) Case "_" GUICtrlSetData($eConsole, GUICtrlRead($eConsole)&" ") Case "/" GUICtrlSetData($eConsole, GUICtrlRead($eConsole)&@CRLF) EndSwitch Next Return 0 EndFunc   Func _MatchBracket($Code,$iStart=1,$iEnd=0) If $iEnd<1 Then $iEnd=StringLen($Code) Local $Open=0 For $i=$iStart To $iEnd Switch StringMid($Code,$i,1) Case '[' $Open+=1 Case ']' $Open-=1 If $Open=0 Then Return $i If $Open<0 Then Return SetError(1,0,$i) EndSwitch Next If $Open>0 Then Return SetError(2,0,$i) Return 0 EndFunc
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.
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion   set target=M E T H I N K S @ I T @ I S @ L I K E @ A @ W E A S E L set chars=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @   set tempcount=0 for %%i in (%target%) do ( set /a tempcount+=1 set target!tempcount!=%%i ) call:parent   echo %target% echo --------------------------------------------------------   :loop call:fitness parent set currentfit=%errorlevel% if %currentfit%==28 goto end echo %parent% - %currentfit% [%attempts%] set attempts=0   :innerloop set /a attempts+=1 title Attemps - %attempts% call:mutate %parent% call:fitness tempparent set newfit=%errorlevel% if %newfit% gtr %currentfit% ( set tempcount=0 set "parent=" for %%i in (%tempparent%) do ( set /a tempcount+=1 set parent!tempcount!=%%i set parent=!parent! %%i ) goto loop ) goto innerloop   :end echo %parent% - %currentfit% [%attempts%] echo Done. exit /b   :parent set "parent=" for /l %%i in (1,1,28) do ( set /a charchosen=!random! %% 27 + 1 set tempcount=0 for %%j in (%chars%) do ( set /a tempcount+=1 if !charchosen!==!tempcount! ( set parent%%i=%%j set parent=!parent! %%j ) ) ) exit /b   :fitness set fitness=0 set array=%1 for /l %%i in (1,1,28) do if !%array%%%i!==!target%%i! set /a fitness+=1 exit /b %fitness%   :mutate set tempcount=0 set returnarray=tempparent set "%returnarray%=" for %%i in (%*) do ( set /a tempcount+=1 set %returnarray%!tempcount!=%%i set %returnarray%=!%returnarray%! %%i ) set /a tomutate=%random% %% 28 + 1 set /a mutateto=%random% %% 27 + 1 set tempcount=0 for %%i in (%chars%) do ( set /a tempcount+=1 if %mutateto%==!tempcount! ( set %returnarray%!tomutate!=%%i ) ) set "%returnarray%=" for /l %%i in (1,1,28) do set %returnarray%=!%returnarray%! !%returnarray%%%i! exit /b  
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
#L.2B.2B
L++
(defn int fib (int n) (return (? (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))) (main (prn (fib 30)))
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Ursala
Ursala
#import std #import nat   factors "n" = (filter not remainder/"n") nrange(1,"n")
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#VBA
VBA
Function Factors(x As Integer) As String Application.Volatile Dim i As Integer Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors End If Next i If x <> 1 Then Factors = Factors & ", " & corresponding_factors End Function
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Liberty_BASIC
Liberty BASIC
'Try this hq9+ program - "hq9+HqQ+Qq" Prompt "Please input your hq9+ program."; code$ Print hq9plus$(code$) End   Function hq9plus$(code$) For i = 1 to Len(code$) Select Case Case Upper$(Mid$(code$, i, 1)) = "H" hq9plus$ = hq9plus$ + "Hello, world!" Case Upper$(Mid$(code$, i, 1)) = "Q" hq9plus$ = hq9plus$ + code$ Case Mid$(code$, i, 1) = "9" For bottles = 99 To 1 Step -1 hq9plus$ = hq9plus$ + str$(bottles) + " bottle" If (bottles > 1) Then hq9plus$ = hq9plus$ + "s" hq9plus$ = hq9plus$ + " of beer on the wall, " + str$(bottles) + " bottle" If (bottles > 1) Then hq9plus$ = hq9plus$ + "s" hq9plus$ = hq9plus$ + " of beer," + chr$(13) + chr$(10) + "Take one down, pass it around, " + str$(bottles - 1) + " bottle" If (bottles > 2) Or (bottles = 1) Then hq9plus$ = hq9plus$ + "s" hq9plus$ = hq9plus$ + " of beer on the wall." + chr$(13) + chr$(10) Next bottles hq9plus$ = hq9plus$ + "No more bottles of beer on the wall, no more bottles of beer." _ + chr$(13) + chr$(10) + "Go to the store and buy some more, 99 bottles of beer on the wall." Case Mid$(code$, i, 1) = "+" accumulator = (accumulator + 1) End Select If Mid$(code$, i, 1) <> "+" Then hq9plus$ = hq9plus$ + chr$(13) + chr$(10) End If Next i hq9plus$ = Left$(hq9plus$, (Len(hq9plus$) - 2)) End Function
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
#J
J
require'strings regex'   markovLexer =: verb define rules =. LF cut TAB&=`(,:&' ')}y rules =. a: -.~ (dltb@:{.~ i:&'#')&.> rules rules =. 0 _1 {"1 '\s+->\s+' (rxmatch rxcut ])S:0 rules (,. ] (}.&.>~ ,. ]) ('.'={.)&.>)/ |: rules )     replace =: dyad define 'index patternLength replacement'=. x 'head tail' =. index split y head, replacement, patternLength }. tail )   matches =: E. i. 1:   markov =: dyad define ruleIdx =. 0 [ rules =. markovLexer x while. ruleIdx < #rules do. 'pattern replacement terminating' =. ruleIdx { rules ruleIdx =. 1 + ruleIdx if. (#y) > index =. pattern matches y do. y =. (index ; (#pattern) ; replacement) replace y ruleIdx =. _ * terminating end. end. y )
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.
#jq
jq
# n is assumed to be the number of times baz has been previously called: def baz(n): if n==0 then error("U0") elif n==1 then error("U1") else "Goodbye" end;   def bar(n): baz(n);   def foo: (try bar(0) catch if . == "U0" then "We caught U0" else error(.) end), (try bar(1) catch if . == "U0" then "We caught U0" else error(.) end);   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.
#Julia
Julia
struct U0 <: Exception end struct U1 <: Exception end   function foo() for i in 1:2 try bar() catch err if isa(err, U0) println("catched U0") else rethrow(err) end end end end   function bar() baz() end   function baz() if isdefined(:_called) && _called throw(U1()) else global _called = true throw(U0()) end end   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.
#Kotlin
Kotlin
// version 1.0.6   class U0 : Throwable("U0 occurred") class U1 : Throwable("U1 occurred")   fun foo() { for (i in 1..2) { try { bar(i) } catch(e: U0) { println(e.message) } } }   fun bar(i: Int) { baz(i) }   fun baz(i: Int) { when (i) { 1 -> throw U0() 2 -> throw U1() } }   fun main(args: Array<String>) { 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
#Forth
Forth
: f ( -- ) 1 throw ." f " ; \ will throw a "1" : g ( -- ) 0 throw ." g " ; \ does not throw
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Enum ErrorType myError = 1000 End Enum   Sub foo() Err = 1000 ' raise a user-defined error End Sub   Sub callFoo() foo() Dim As Long errNo = Err ' cache Err in case it's reset by a different function Select Case errNo Case 0 ' No error (system defined) Case 1 To 17 ' System defined runtime errors Case myError: ' catch myError Print "Caught myError : Error number"; errNo Case Else ' catch any other type of errors here End Select ' add any clean-up code here End Sub   callfoo() Print Print "Press any key to quit" 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
#DBL
DBL
XCALL SPAWN ("ls *.jpg > file.txt")  ;execute command and continue XCALL EXEC ("script.sh")  ;execute script or binary and exit STOP '@/bin/ls *.jpg > file.txt'  ;exit and execute command
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
#Applesoft_BASIC
Applesoft BASIC
100 N = 4 : GOSUB 200"FACTORIAL 110 PRINT N 120 END   200 N = INT(N) 210 IF N > 1 THEN FOR I = N - 1 TO 2 STEP -1 : N = N * I : NEXT I 220 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
#Lambdatalk
Lambdatalk
  {def ^ {def *^ {lambda {:base :exponent :acc} {if {= :exponent 0} then :acc else {*^ :base {- :exponent 1} {* :acc :base}}}}} {lambda {:base :exponent} {*^ :base :exponent 1}}} -> ^   {^ 2 3} -> 8 {^ {/ 1 2} 3} -> 0.125 // No rational type as primitives {^ 0.5 3} -> 0.125  
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
#Liberty_BASIC
Liberty BASIC
  print " 11^5 = ", floatPow( 11, 5 ) print " (-11)^5 = ", floatPow( -11, 5 ) print " 11^( -5) = ", floatPow( 11, -5 ) print " 3.1416^3 = ", floatPow( 3.1416, 3 ) print " 0^2 = ", floatPow( 0, 2 ) print " 2^0 = ", floatPow( 2, 0 ) print " -2^0 = ", floatPow( -2, 0 )   end   function floatPow( a, b) if a <>0 then m =1 if b =abs( b) then for n =1 to b m =m *a next n else m =1 /floatPow( a, 0 - b) ' LB has no unitary minus operator. end if else m =0 end if floatPow =m end function  
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.
#PowerShell
PowerShell
  function When-Condition { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, Position=0)] [bool] $Test1,   [Parameter(Mandatory=$true, Position=1)] [bool] $Test2,   [Parameter(Mandatory=$true, Position=2)] [scriptblock] $Both,   [Parameter(Mandatory=$true, Position=3)] [scriptblock] $First,   [Parameter(Mandatory=$true, Position=4)] [scriptblock] $Second,   [Parameter(Mandatory=$true, Position=5)] [scriptblock] $Neither )   if ($Test1 -and $Test2) { return (&$Both) } elseif ($Test1 -and -not $Test2) { return (&$First) } elseif (-not $Test1 -and $Test2) { return (&$Second) } else { return (&$Neither) } }  
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
#Salmon
Salmon
iterate (x; [1...100]) ((x % 15 == 0) ? "FizzBuzz" : ((x % 3 == 0) ? "Fizz" : ((x % 5 == 0) ? "Buzz" : x)))!;
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.
#PureBasic
PureBasic
EnableExplicit DisableDebugger Define StartTime.i=ElapsedMilliseconds()   Procedure.b IsPrime(n.i) Define i.i=5 If n<2 : ProcedureReturn #False : EndIf If n%2=0 : ProcedureReturn Bool(n=2) : EndIf If n%3=0 : ProcedureReturn Bool(n=3) : EndIf While i*i<=n If n%i=0 : ProcedureReturn #False : EndIf i+2 If n%i=0 : ProcedureReturn #False : EndIf i+4 Wend ProcedureReturn #True EndProcedure   If OpenConsole("Extensible prime generator") Define c.i=0, n.i=2 Print("First twenty: ") While c<20 If IsPrime(n) Print(Str(n)+" ") c+1 EndIf n+1 Wend   Print(~"\nBetween 100 and 150: ") For n=100 To 150 If IsPrime(n) Print(Str(n)+" ") EndIf Next   Print(~"\nNumber beween 7'700 and 8'000: ") c=0 For n=7700 To 8000 c+IsPrime(n) Next Print(Str(c))   Print(~"\n10'000th prime: ") c=0 : n=1 While c<10000 n+1 c+IsPrime(n) Wend Print(Str(n)) EndIf Print(~"\nRuntime milliseconds: "+ Str(ElapsedMilliseconds()-StartTime)) Input()
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.
#AWK
AWK
BEGIN { bf=ARGV[1]; ARGV[1] = "" compile(bf) execute() }   # Strips non-instructions, builds the jump table. function compile(s, i,j,k,f) { c = split(s, src, "") j = 0 for(i = 1; i <= c; i++) { if(src[i] ~ /[\-\+\[\]\<\>,\.]/) code[j++] = src[i]   if(src[i] == "[") { marks[j] = 1 } else if(src[i] == "]") { f = 0 for(k = j; k > 0; k--) { if(k in marks) { jump[k-1] = j - 1 jump[j-1] = k - 1 f = 1 delete marks[k] break } } if(!f) { print "Unmatched ]" exit 1 } } } }   function execute( pc,p,i) { pc = p = 0 while(pc in code) { i = code[pc]   if(i == "+") arena[p]++ else if(i == "-") arena[p]-- else if(i == "<") p-- else if(i == ">") p++ else if(i == ".") printf("%c", arena[p]) else if(i == ",") { while(1) { if (goteof) break if (!gotline) { gotline = getline if(!gotline) goteof = 1 if (goteof) break line = $0 } if (line == "") { gotline=0 m[p]=10 break } if (!genord) { for(i=1; i<256; i++) ord[sprintf("%c",i)] = i genord=1 } c = substr(line, 1, 1) line=substr(line, 2) arena[p] = ord[c] break }   } else if((i == "[" && arena[p] == 0) || (i == "]" && arena[p] != 0)) pc = jump[pc] pc++ } }  
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.
#BBC_BASIC
BBC BASIC
target$ = "METHINKS IT IS LIKE A WEASEL" parent$ = "IU RFSGJABGOLYWF XSMFXNIABKT" mutation_rate = 0.5 children% = 10   DIM child$(children%)   REPEAT bestfitness = 0 bestindex% = 0 FOR index% = 1 TO children% child$(index%) = FNmutate(parent$, mutation_rate) fitness = FNfitness(target$, child$(index%)) IF fitness > bestfitness THEN bestfitness = fitness bestindex% = index% ENDIF NEXT index%   parent$ = child$(bestindex%) PRINT parent$ UNTIL parent$ = target$ END   DEF FNfitness(text$, ref$) LOCAL I%, F% FOR I% = 1 TO LEN(text$) IF MID$(text$, I%, 1) = MID$(ref$, I%, 1) THEN F% += 1 NEXT = F% / LEN(text$)   DEF FNmutate(text$, rate) LOCAL C% IF rate > RND(1) THEN C% = 63+RND(27) IF C% = 64 C% = 32 MID$(text$, RND(LEN(text$)), 1) = CHR$(C%) ENDIF = text$
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
#LabVIEW
LabVIEW
  1) basic version {def fib1 {lambda {:n} {if {< :n 3} then 1 else {+ {fib1 {- :n 1}} {fib1 {- :n 2}}} }}}   {fib1 16} -> 987 (CPU ~ 16ms) {fib1 30} = 832040 (CPU > 12000ms)   2) tail-recursive version {def fib2 {def fib2.r {lambda {:a :b :i} {if {< :i 1} then :a else {fib2.r :b {+ :a :b} {- :i 1}} }}} {lambda {:n} {fib2.r 0 1 :n}}}   {fib2 16} -> 987 (CPU ~ 1ms) {fib2 30} -> 832040 (CPU ~2ms) {fib2 1000} -> 4.346655768693743e+208 (CPU ~ 22ms)   3) Dijkstra Algorithm {def fib3 {def fib3.r {lambda {:a :b :p :q :count} {if {= :count 0} then :b else {if {= {% :count 2} 0} then {fib3.r :a :b {+ {* :p :p} {* :q :q}} {+ {* :q :q} {* 2 :p :q}} {/ :count 2}} else {fib3.r {+ {* :b :q} {* :a :q} {* :a :p}} {+ {* :b :p} {* :a :q}}  :p :q {- :count 1}} }}}} {lambda {:n} {fib3.r 1 0 0 1 :n} }}   {fib3 16} -> 987 (CPU ~ 2ms) {fib3 30} -> 832040 (CPU ~ 2ms) {fib3 1000} -> 4.346655768693743e+208 (CPU ~ 3ms)   4) memoization {def fib4 {def fib4.m {array.new}} // init an empty array {def fib4.r {lambda {:n} {if {< :n 2} then {array.get {array.set! {fib4.m} :n 1} :n} // init with 1,1 else {if {equal? {array.get {fib4.m} :n} undefined} // if not exists then {array.get {array.set! {fib4.m} :n {+ {fib4.r {- :n 1}} {fib4.r {- :n 2}}}} :n} // compute it else {array.get {fib4.m} :n} }}}} // else get it {lambda {:n} {fib4.r :n} {fib4.m} }} // display the number AND all its predecessors -> fib4 {fib4 90} -> 4660046610375530000 [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418, 317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155, 165580141,267914296,433494437,701408733,1134903170,1836311903,2971215073,4807526976,7778742049,12586269025, 20365011074,32951280099,53316291173,86267571272,139583862445,225851433717,365435296162,591286729879,956722026041, 1548008755920,2504730781961,4052739537881,6557470319842,10610209857723,17167680177565,27777890035288,44945570212853, 72723460248141,117669030460994,190392490709135,308061521170129,498454011879264,806515533049393,1304969544928657, 2111485077978050,3416454622906707,5527939700884757,8944394323791464,14472334024676220,23416728348467684, 37889062373143900,61305790721611580,99194853094755490,160500643816367070,259695496911122560,420196140727489660, 679891637638612200,1100087778366101900,1779979416004714000,2880067194370816000,4660046610375530000]   5) Binet's formula (non recursive) {def fib5 {lambda {:n} {let { {:n :n} {:sqrt5 {sqrt 5}} } {round {/ {- {pow {/ {+ 1 :sqrt5} 2} :n} {pow {/ {- 1 :sqrt5} 2} :n}} :sqrt5}}} }}   {fib5 16} -> 987 (CPU ~ 1ms) {fib5 30} -> 832040 (CPU ~ 1ms) {fib5 1000} -> 4.346655768693743e+208 (CPU ~ 1ms)    
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Verilog
Verilog
  module main; integer i, n;   initial begin n = 45;   $write(n, " =>"); for(i = 1; i <= n / 2; i = i + 1) if(n % i == 0) $write(i); $display(n); $finish ; end endmodule  
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Lua
Lua
  function runCode( code ) local acc, lc = 0 for i = 1, #code do lc = code:sub( i, i ):upper() if lc == "Q" then print( lc ) elseif lc == "H" then print( "Hello, World!" ) elseif lc == "+" then acc = acc + 1 elseif lc == "9" then for j = 99, 1, -1 do if j > 1 then print( string.format( "%d bottles of beer on the wall\n%d bottles of beer\nTake one down, pass it around\n%d bottles of beer on the wall\n", j, j, j - 1 ) ) else print( "1 bottle of beer on the wall\n1 bottle of beer\nTake one down and pass it around\nno more bottles of beer on the wall\n\n".. "No more bottles of beer on the wall\nNo more bottles of beer\n".. "Go to the store and buy some more\n99 bottles of beer on the wall.\n" ) end end end end end  
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
#Java
Java
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;   public class Markov {   public static void main(String[] args) throws IOException {   List<String[]> rules = readRules("markov_rules.txt"); List<String> tests = readTests("markov_tests.txt");   Pattern pattern = Pattern.compile("^([^#]*?)\\s+->\\s+(\\.?)(.*)");   for (int i = 0; i < tests.size(); i++) { String origTest = tests.get(i);   List<String[]> captures = new ArrayList<>(); for (String rule : rules.get(i)) { Matcher m = pattern.matcher(rule); if (m.find()) { String[] groups = new String[m.groupCount()]; for (int j = 0; j < groups.length; j++) groups[j] = m.group(j + 1); captures.add(groups); } }   String test = origTest; String copy = test; for (int j = 0; j < captures.size(); j++) { String[] c = captures.get(j); test = test.replace(c[0], c[2]); if (c[1].equals(".")) break; if (!test.equals(copy)) { j = -1; // redo loop copy = test; } } System.out.printf("%s\n%s\n\n", origTest, test); } }   private static List<String> readTests(String path) throws IOException { return Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8); }   private static List<String[]> readRules(String path) throws IOException { String ls = System.lineSeparator(); String lines = new String(Files.readAllBytes(Paths.get(path)), "UTF-8"); List<String[]> rules = new ArrayList<>(); for (String line : lines.split(ls + ls)) rules.add(line.split(ls)); return rules; } }
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.
#langur
langur
val .U0 = h{"msg": "U0"} val .U1 = h{"msg": "U1"}   val .baz = f(.i) throw if(.i==0: .U0; .U1) val .bar = f(.i) .baz(.i)   val .foo = f() { for .i in [0, 1] { .bar(.i) catch if _err["msg"] == .U0["msg"] { writeln "caught .U0 in .foo()" } else { throw } } }   .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.
#Lasso
Lasso
define try(exception) => { local( gb = givenblock, error ) handle => { // Only relay error if it's not the specified exception if(#error) => { if(#error->get(2) == #exception) => { stdoutnl('Handled exception: '+#error->get(2)) else stdoutnl('Throwing exception: '+#error->get(2)) fail(:#error) } } } protect => { handle_error => { #error = (:error_code,error_msg,error_stack) } #gb() } }   define foo => { stdoutnl('foo') try('U0') => { bar } try('U0') => { bar } }   define bar => { stdoutnl('- bar') baz() }   define baz => { stdoutnl(' - baz') var(bazzed) ? fail('U1') | $bazzed = true fail('U0') }
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.
#Lua
Lua
local baz_counter=1 function baz() if baz_counter==1 then baz_counter=baz_counter+1 error("U0",3)--3 sends it down the call stack. elseif baz_counter==2 then error("U1",3)--3 sends it down the call stack. end end   function bar() baz() end   function foo() function callbar() local no_err,result = pcall(bar) --pcall is a protected call which catches errors. if not no_err then --If there are no errors, pcall returns true. if not result:match("U0") then --If the error is not a U0 error, rethrow it. error(result,2) --2 is the distance down the call stack to send --the error. We want it to go back to the callbar() call. end end end callbar() callbar() 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
#Gambas
Gambas
Public Sub Main() Dim iInteger As Integer   MakeError DivError   iInteger = "2.54"   Catch Print Error.Text   End '______________________ Public Sub DivError()   Print 10 / 0   Catch Print Error.Text   End '______________________ Public Sub MakeError()   Error.Raise("My Error")   Catch Print Error.Text   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
#DCL
DCL
Directory
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
#Delphi
Delphi
program ExecuteSystemCommand;   {$APPTYPE CONSOLE}   uses Windows, ShellApi;   begin ShellExecute(0, nil, 'cmd.exe', ' /c dir', nil, SW_HIDE); end.
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
#Arendelle
Arendelle
< n > { @n = 0 , ( return , 1 ) , ( return , @n * !factorial( @n - ! ) ) }