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/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 langua... | #UNIX_Shell | UNIX Shell | if2() {
if eval "$1"; then
if eval "$2"; then eval "$3"; else eval "$4"; fi
else
if eval "$2"; then eval "$5"; else eval "$6"; fi
fi
} |
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)
... | #Sidef | Sidef | { |i|
if (i %% 3) {
print "Fizz"
i %% 5 && print "Buzz"
print "\n"
}
elsif (i %% 5) { say "Buzz" }
else { say i }
} * 100 |
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 thi... | #Swift | Swift | import Foundation
func soeDictOdds() -> UnfoldSequence<Int, Int> {
var bp = 5; var q = 25
var bps: UnfoldSequence<Int, Int>.Iterator? = nil
var dict = [9: 6] // Dictionary<Int, Int>(9 => 6)
return sequence(state: 2, next: { n in
if n < 9 { if n < 3 { n = 3; return 2 }; defer {n += 2}; return n }
while... |
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:... | #Clojure | Clojure | (ns brainfuck)
(def ^:dynamic *input*)
(def ^:dynamic *output*)
(defrecord Data [ptr cells])
(defn inc-ptr [next-cmd]
(fn [data]
(next-cmd (update-in data [:ptr] inc))))
(defn dec-ptr [next-cmd]
(fn [data]
(next-cmd (update-in data [:ptr] dec))))
(defn inc-cell [next-cmd]
(fn [data]
(next-... |
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.... | #D | D | import std.stdio, std.random, std.algorithm, std.range, std.ascii;
enum target = "METHINKS IT IS LIKE A WEASEL"d;
enum C = 100; // Number of children in each generation.
enum P = 0.05; // Mutation probability.
enum fitness = (dchar[] s) => target.zip(s).count!q{ a[0] != a[1] };
dchar rnd() { return (uppercase ~ " ")... |
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 ... | #LiveCode | LiveCode | -- Iterative, translation of the basic version.
function fibi n
put 0 into aa
put 1 into b
repeat with i = 1 to n
put aa + b into temp
put b into aa
put temp into b
end repeat
return aa
end fibi
-- Recursive
function fibr n
if n <= 1 then
return n
else
... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Python | Python | $ "bottles.qky" loadfile ( if required, the source code for this can be found at
http://rosettacode.org/wiki/99_bottles_of_beer#Quackery )
[ stack ] is accumulator ( --> s )
[ stack ] is sourcecode ( --> s )
[ say "Hello, world!" cr ] is H.HQ9+ ... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Quackery | Quackery | $ "bottles.qky" loadfile ( if required, the source code for this can be found at
http://rosettacode.org/wiki/99_bottles_of_beer#Quackery )
[ stack ] is accumulator ( --> s )
[ stack ] is sourcecode ( --> s )
[ say "Hello, world!" cr ] is H.HQ9+ ... |
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> <wh... | #PureBasic | PureBasic | Structure mRule
pattern.s
replacement.s
isTerminal.i
EndStructure
Procedure parseRule(text.s, List rules.mRule())
#tab = 9: #space = 32: #whiteSpace$ = Chr(#space) + Chr(#tab)
Protected tLen, cPtr, nChar.c, pEnd, pLast, pattern.s
cPtr = 1
If FindString(#whiteSpace$, Left(text, cPtr), 1): ProcedureRetu... |
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 rais... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const EXCEPTION: U0 is enumlit;
const EXCEPTION: U1 is enumlit;
const proc: baz (in integer: num) is func
begin
if num = 1 then
raise U0;
else
raise U1;
end if;
end func;
const proc: bar (in integer: num) is func
begin
baz(num);
end func;
const proc:... |
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 rais... | #Sidef | Sidef | func baz(i) { die "U#{i}" };
func bar(i) { baz(i) };
func foo {
[0, 1].each { |i|
try { bar(i) }
catch { |_, msg|
msg ~~ /^U0/ ? say "Function foo() caught exception U0"
: die msg; # re-raise the exception
};
}
}
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 rais... | #Smalltalk | Smalltalk |
Exception subclass: #U0.
Exception subclass: #U1.
Object subclass: Foo [
bazCount := 0.
foo
[2 timesRepeat:
[ "==>" [self bar] "<=="
on: U0
do:
[:sig |
'Call to bar was aborted by exception U0' printNl.
... |
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
| #MATLAB | MATLAB | >> error 'Help'
??? Help |
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
| #Modula-3 | Modula-3 | EXCEPTION EndOfFile;
EXCEPTION Error(TEXT); |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Io | Io | System runCommand("ls") stdout println |
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
| #IS-BASIC | IS-BASIC | 100 EXT "dir" |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #J | J | load'task'
NB. Execute a command and wait for it to complete
shell 'dir'
NB. Execute a command but don't wait for it to complete
fork 'notepad'
NB. Execute a command and capture its stdout
stdout =: shell 'dir'
NB. Execute a command, provide it with stdin,
NB. and capture its stdout
stdin =: 'bl... |
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 iterat... | #Babel | Babel | ((main
{(0 1 2 3 4 5 6 7 8 9 10)
{fact ! %d nl <<}
each})
(fact
{({dup 0 =}{ zap 1 }
{dup 1 =}{ zap 1 }
{1 }{ <- 1 {iter 1 + *} -> 1 - times })
cond})) |
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 ov... | #Pascal | Pascal | Program ExponentiationOperator(output);
function intexp (base, exponent: integer): longint;
var
i: integer;
begin
if (exponent < 0) then
if (base = 1) then
intexp := 1
else
intexp := 0
else
begin
intexp := 1;
for i := 1 to exponent do
intexp := int... |
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 langua... | #Ursala | Ursala | iftwo("p","q") <"both","justp","justq","neither"> =
"p"?(
"q"?("both","justp"),
"q"?("justq","neither")) |
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 langua... | #Wren | Wren | class IfBoth {
construct new(cond1, cond2) {
_cond1 = cond1
_cond2 = cond2
}
elseFirst(func) {
if (_cond1 && !_cond2) func.call()
return this
}
elseSecond(func) {
if (_cond2 && !_cond1) func.call()
return this
}
elseNeither(func) {
... |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #Simula | Simula | begin
integer i;
for i := 1 step 1 until 100 do
begin
boolean fizzed;
fizzed := 0 = mod(i, 3);
if fizzed then
outtext("Fizz");
if mod(i, 5) = 0 then
outtext("Buzz")
else if not fizzed then
outint(i, 3);
outimage
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 thi... | #Tcl | Tcl | package require Tcl 8.6
# An iterative version of the Sieve of Eratosthenes.
# Effective limit is the size of memory.
coroutine primes apply {{} {
yield
while 1 {yield [coroutine primes_[incr p] apply {{} {
yield [info coroutine]
set plist {}
for {set n 2} true {incr n} {
set found 0
foreach p $p... |
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:... | #CLU | CLU | tape = cluster is new, left, right, get_cell, set_cell
ac = array[char]
rep = record [
cells: ac,
index: int
]
new = proc () returns (cvt)
t: rep := rep${
cells: ac$predict(0, 30000),
index: 0
}
ac$addh(t.cells, '\000')
return(t... |
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.... | #Delphi | Delphi | pragma.syntax("0.9")
pragma.enable("accumulator")
def target := "METHINKS IT IS LIKE A WEASEL"
def alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
def C := 100
def RATE := 0.05
def randomCharString() {
return E.toString(alphabet[entropy.nextInt(alphabet.size())])
}
def fitness(string) {
return accum 0 for i => ch... |
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 ... | #LLVM | LLVM | ; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such ... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Racket | Racket | #lang racket
; if we `for` over the port, we won't have the program in memory for 'Q'
(define (parse-HQ9+ the-program)
(define oTW " on the wall")
(and ; ensures the accumulator is never seen!
(for/fold ((A 0))
((token (in-string the-program)))
(case token
((#\H) (display "hello, world") A)
... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Raku | Raku | class HQ9Interpreter {
has @!code;
has $!accumulator;
has $!pointer;
method run ($code) {
@!code = $code.comb;
$!accumulator = 0;
$!pointer = 0;
while $!pointer < @!code {
given @!code[$!pointer].lc {
when 'h' { say 'Hello world!' }
... |
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> <wh... | #Python | Python | import re
def extractreplacements(grammar):
return [ (matchobj.group('pat'), matchobj.group('repl'), bool(matchobj.group('term')))
for matchobj in re.finditer(syntaxre, grammar)
if matchobj.group('rule')]
def replace(text, replacements):
while True:
for pat, repl, ter... |
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 rais... | #Swift | Swift | enum MyException : ErrorType {
case U0
case U1
}
func foo() throws {
for i in 0 ... 1 {
do {
try bar(i)
} catch MyException.U0 {
print("Function foo caught exception U0")
}
}
}
func bar(i: Int) throws {
try baz(i) // Nest those calls
}
func baz(i: Int) throws {
if i == 0 {
... |
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 rais... | #Tcl | Tcl | package require Tcl 8.5
proc foo {} {
set code [catch {bar} ex options]
if {$code == 1} {
switch -exact -- $ex {
U0 {puts "caught exception U0"}
default {return -options $options $ex ;# re-raise exception}
}
}
}
proc bar {} {baz}
# create an alias to pass ... |
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
| #MOO | MOO | raise(E_PERM); |
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
| #Nanoquery | Nanoquery | try
invalid "this statement will fail"
catch e
println "caught an exception"
println e
end try |
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
| #Java | Java | import java.util.Scanner;
import java.io.*;
public class Program {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir");//Windows command, use "ls -oa" for UNIX
Scanner sc = new Scanner(p.getInputStream());
while (sc.hasNext()) System... |
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
| #JavaScript | JavaScript | var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause"); |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #BaCon | BaCon | ' Factorial
FUNCTION factorial(NUMBER n) TYPE NUMBER
IF n <= 1 THEN
RETURN 1
ELSE
RETURN n * factorial(n - 1)
ENDIF
END FUNCTION
n = VAL(TOKEN$(ARGUMENT$, 2))
PRINT n, factorial(n) FORMAT "%ld! = %ld\n" |
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 ov... | #Perl | Perl | #!/usr/bin/perl -w
use strict ;
sub expon {
my ( $base , $expo ) = @_ ;
if ( $expo == 0 ) {
return 1 ;
}
elsif ( $expo == 1 ) {
return $base ;
}
elsif ( $expo > 1 ) {
my $prod = 1 ;
foreach my $n ( 0..($expo - 1) ) {
$prod *= $base ;
}
return $prod ;
}
el... |
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 langua... | #XBS | XBS | #>
newsyntax
@in:CH
@token:does
@CH:"function(Stack){
this.Next(Stack);
this.ChunkWrite(Stack,this.ParseExpression(Stack));
this.TestNext(Stack,\"Bracket\",\"TK_BOPEN\");
this.Move(Stack,2);
this.CodeBlock(Stack);
this.JumpBack(Stack);
this.OpenChunk(Stack);
while(this.CheckNext(Stack,\"Identifier\",\"otherwise... |
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 langua... | #Z80_Assembly | Z80 Assembly | cp b
jr nz,B_False
cp c
jr z,doubleTrue
;B true, C false
;your code goes here
jp done
B_False:
cp c
jr nz,doubleFalse
;B false, C true
;your code goes here
jp done
doubleTrue:
;your code goes here
jp done
doubleFalse:
;your code goes here
jp done
done:
;rest of prog... |
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)
... | #SkookumScript | SkookumScript |
1.to 100
[
println(
if idx.mod(15) = 0 ["FizzBuzz"]
idx.mod(3) = 0 ["Fizz"]
idx.mod(5) = 0 ["Buzz"]
else [idx])
]
|
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 thi... | #VBA | VBA | Option Explicit
Sub Main()
Dim Primes() As Long, n As Long, temp$
Dim t As Single
t = Timer
n = 133218295 'limit for an Array of Longs with VBA on my computer
Primes = ListPrimes(n)
Debug.Print "For N = " & Format(n, "#,##0") & ", execution time : " & _
Format(Timer - t, "0.000 s") & ", " & ... |
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:... | #COBOL | COBOL | pointer_alpha = 1/0
pointer_numeric = 1/0
tape_behind = ''
tape_ahead = 1/0
tape_pos = 0 # only for debugging
array_behind = 1/0
array_ahead = ''
set_tape_ahead = array_ahead
array_ahead = 1/0
#
shift
comefrom if array_ahead is array_ahead
cdr = 1/0
cdr = array_ahead
shift_tail = cdr
new_cell
comefrom shi... |
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.... | #E | E | pragma.syntax("0.9")
pragma.enable("accumulator")
def target := "METHINKS IT IS LIKE A WEASEL"
def alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
def C := 100
def RATE := 0.05
def randomCharString() {
return E.toString(alphabet[entropy.nextInt(alphabet.size())])
}
def fitness(string) {
return accum 0 for i => ch... |
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 ... | #Logo | Logo | to fib :n [:a 0] [:b 1]
if :n < 1 [output :a]
output (fib :n-1 :b :a+:b)
end |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #REXX | REXX | /*REXX program implements the HQ9+ language. ───────────────────────────────────────*/
arg pgm . /*obtain optional argument.*/
accumulator=0 /*assign default to accum. */
do instructions=1 for length(pgm); ... |
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> <wh... | #Racket | Racket |
#lang racket
(struct -> (A B))
(struct ->. (A B))
(define ((Markov-algorithm . rules) initial-string)
(let/cc stop
; rewriting rules
(define (rewrite rule str)
(match rule
[(-> a b) (cond [(replace a str b) => apply-rules]
[else str])]
[(->. a b) (cond [... |
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> <wh... | #Raku | Raku | grammar Markov {
token TOP {
^ [^^ [<rule> | <comment>] $$ [\n|$]]* $
{ make $<rule>>>.ast }
}
token comment {
<before ^^> '#' \N*
{ make Nil }
}
token ws {
[' '|\t]*
}
rule rule {
<before ^^>$<pattern>=[\N+?] '->'
$<terminal>=[\.]?$<re... |
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 rais... | #TXR | TXR | @(defex u0)
@(defex u1)
@(define baz (x))
@ (cases)
@ (bind x "0")
@ (throw u0 "text0")
@ (or)
@ (bind x "1")
@ (throw u1 "text1")
@ (end)
@(end)
@(define bar (x))
@ (baz x)
@(end)
@(define foo ())
@ (next :list @'("0" "1"))
@ (collect)
@num
@ (try)
@ (bar num)
@ (catch u0 (arg))
@ (ou... |
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 rais... | #Ursala | Ursala | #import std
baz =
~&?(
~&h?(
:/'baz succeeded with this input:',
<'baz threw a user-defined empty string exception','U1'>!%),
<'baz threw a user-defined empty file exception','U0'>!%)
bar = :/'bar received this result from normal termination of baz:'+ baz
#executable&
foo =
guard(
:/'... |
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 rais... | #Visual_Basic_.NET | Visual Basic .NET | Class U0
Inherits Exception
End Class
Class U1
Inherits Exception
End Class
Module Program
Sub Main()
Foo()
End Sub
Sub Foo()
Try
Bar()
Bar()
Catch ex As U0
Console.WriteLine(ex.GetType.Name & " caught.")
End Try
End Sub
... |
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
| #Nemerle | Nemerle | // define a new exception
class MyException : Exception
{
...
}
// throw an exception
Foo() : void
{
throw MyException();
}
// catching exceptions
try {
Foo();
}
catch { // catch block uses pattern matching syntax
|e is MyException => ... // handle exception
|_ => throw e // rethrow unhandled ex... |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
-- =============================================================================
class RExceptions public
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method test() public signals RExceptions.TakeExcep... |
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
| #Joy | Joy | "ls" system. |
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
| #Julia | Julia | run(`ls`) |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #K | K | \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 iterat... | #bash | bash | factorial()
{
if [ $1 -le 1 ]
then
echo 1
else
result=$(factorial $[$1-1])
echo $((result*$1))
fi
}
|
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 ov... | #Phix | Phix | with javascript_semantics
function powir(atom b, integer i)
atom res = 1
if i<0 then {b,i} = {1/b,abs(i)} end if
while i do
if and_bits(i,1) then res *= b end if
b *= b
i = floor(i/2)
end while
return res
end function
?powir(-3,-5)
?power(-3,-5)
|
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 langua... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DEF FN i()=((NOT (a OR b))+2*(a AND NOT b)+3*(b AND NOT a)+4*(a AND b)): REM the function can be placed anywhere in the program, but it gets executed faster if it's at the top
20 FOR x=1 TO 20
30 LET a=(x/2)=INT (x/2): REM comparison 1
40 LET b=(x/3)=INT (x/3): REM comparison 2
50 GO TO 50+10*FN i(): REM cases
60 PR... |
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)
... | #Slate | Slate | n@(Integer traits) fizzbuzz
[
output ::= ((n \\ 3) isZero ifTrue: ['Fizz'] ifFalse: ['']) ; ((n \\ 5) isZero ifTrue: ['Buzz'] ifFalse: ['']).
output isEmpty ifTrue: [n printString] ifFalse: [output]
].
1 to: 100 do: [| :i | inform: i fizzbuzz] |
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 thi... | #Wren | Wren | import "/fmt" for Fmt
var primeSieve = Fn.new { |limit|
if (limit < 2) return []
var c = [false] * (limit + 1) // composite = true
c[0] = true
c[1] = true
// no need to process the even numbers > 2
var k = 9
while (k <= limit) {
c[k] = true
k = k + 6
}
k = 25
wh... |
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:... | #Comefrom0x10 | Comefrom0x10 | pointer_alpha = 1/0
pointer_numeric = 1/0
tape_behind = ''
tape_ahead = 1/0
tape_pos = 0 # only for debugging
array_behind = 1/0
array_ahead = ''
set_tape_ahead = array_ahead
array_ahead = 1/0
#
shift
comefrom if array_ahead is array_ahead
cdr = 1/0
cdr = array_ahead
shift_tail = cdr
new_cell
comefrom shi... |
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.... | #EchoLisp | EchoLisp |
(require 'sequences)
(define ALPHABET (list->vector ["A" .. "Z"] ))
(vector-push ALPHABET " ")
(define (fitness source target) ;; score >=0, best is 0
(for/sum [(s source)(t target)]
(if (= s t) 0 1)))
(define (mutate source rate)
(for/string [(s source)]
(if (< (random) rate) [ALPHABET (random 27)] s)))
... |
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 ... | #LOLCODE | LOLCODE |
HAI 1.2
HOW DUZ I fibonacci YR N
EITHER OF BOTH SAEM N AN 1 AN BOTH SAEM N AN 0
O RLY?
YA RLY, FOUND YR 1
NO WAI
I HAS A N1
I HAS A N2
N1 R DIFF OF N AN 1
N2 R DIFF OF N AN 2
N1 R fibonacci N1
N2 R fibonacci N2
FOUND YR SUM OF N1 AN N2
OIC
IF U SAY SO
KTHXBYE
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Ring | Ring |
# Project : Execute HQ9
bottle("hq9+HqQ+Qq")
func bottle(code)
accumulator = 0
for i = 1 to len(code)
switch code[i]
on "h"
see "Hello, world!" + nl
on "H"
see "hello, world!" + nl
on "q"
... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Ruby | Ruby | use std::env;
// HQ9+ requires that '+' increments an accumulator, but it's inaccessible (and thus, unused).
#[allow(unused_variables)]
fn execute(code: &str) {
let mut accumulator = 0;
for c in code.chars() {
match c {
'Q' => println!("{}", code),
'H' => println!("Hello, Wor... |
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> <wh... | #REXX | REXX | /*REXX program executes a Markov algorithm(s) against specified entries. */
parse arg low high . /*allows which ruleset to process. */
if low=='' | low=="," then low=1 /*Not specified? Then use the default.*/
if high=='' | high=="," then high=6 ... |
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 rais... | #Wren | Wren | var U0 = "U0"
var U1 = "U1"
var bazCalled = 0
var baz = Fn.new {
bazCalled = bazCalled + 1
Fiber.abort( (bazCalled == 1) ? U0 : U1 )
}
var bar = Fn.new {
baz.call()
}
var foo = Fn.new {
for (i in 1..2) {
var f = Fiber.new { bar.call() }
f.try()
var err = f.error
i... |
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 rais... | #zkl | zkl | class U0(Exception.Exception){fcn init{Exception.init("U0")}}
class U1(Exception.Exception){fcn init{Exception.init("U1")}}
fcn foo{try{bar(U0)}catch(U0){} bar(U1)}
fcn bar(e){baz(e)}
fcn baz(e){throw(e)}
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
| #Nim | Nim | type SillyError = object of Exception |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Objective-C | Objective-C | @interface MyException : NSException {
//Put specific info in here
}
@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
| #Kotlin | Kotlin | // version 1.0.6
import java.util.Scanner
fun main(args: Array<String>) {
val proc = Runtime.getRuntime().exec("cmd /C dir") // testing on Windows 10
Scanner(proc.inputStream).use {
while (it.hasNextLine()) println(it.nextLine())
}
} |
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
| #Lang5 | Lang5 | 'ls system |
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 iterat... | #BASIC | BASIC | FUNCTION factorial (n AS Integer) AS Integer
DIM f AS Integer, i AS Integer
f = 1
FOR i = 2 TO n
f = f*i
NEXT i
factorial = f
END FUNCTION |
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 ov... | #PicoLisp | PicoLisp | (de ** (X N) # N th power of X
(if (ge0 N)
(let Y 1
(loop
(when (bit? 1 N)
(setq Y (* Y X)) )
(T (=0 (setq N (>> 1 N)))
Y )
(setq X (* X X)) ) )
0 ) ) |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #PL.2FI | PL/I | declare exp generic
(iexp when (fixed, fixed),
fexp when (float, fixed) );
iexp: procedure (m, n) returns (fixed binary (31));
declare (m, n) fixed binary (31) nonassignable;
declare exp fixed binary (31) initial (m), i fixed binary;
if m = 0 & n = 0 then signal error;
if n = 0 then return (1);
do i... |
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)
... | #Small | Small | Integer extend [
fizzbuzz [
| fb |
fb := '%<Fizz|>1%<Buzz|>2' % {
self \\ 3 == 0. self \\ 5 == 0 }.
^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ]
]
]
1 to: 100 do: [ :i | i fizzbuzz displayNl ] |
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 thi... | #Zig | Zig |
const std = @import("std");
const builtin = std.builtin;
const heap = std.heap;
const mem = std.mem;
const meta = std.meta;
fn assertInt(comptime T: type) builtin.TypeInfo.Int {
if (@typeInfo(T) != .Int)
@compileError("data type must be an integer.");
const int = @typeInfo(T).Int;
if (int.is_sig... |
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:... | #Common_Lisp | Common Lisp |
program Execute_Brain;
{$APPTYPE CONSOLE}
uses
Winapi.Windows,
System.SysUtils;
const
DataSize = 1024; // Size of Data segment
MaxNest = 1000; // Maximum nesting depth of []
function Readkey: Char;
var
InputRec: TInputRecord;
NumRead: Cardinal;
... |
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.... | #Elena | Elena | import system'routines;
import extensions;
import extensions'text;
const string Target = "METHINKS IT IS LIKE A WEASEL";
const string AllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const int C = 100;
const real P = 0.05r;
rnd = randomGenerator;
randomChar
= AllowedCharacters[rnd.nextInt(AllowedCharacte... |
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 ... | #LSL | LSL | integer Fibonacci(integer n) {
if(n<2) {
return n;
} else {
return Fibonacci(n-1)+Fibonacci(n-2);
}
}
default {
state_entry() {
integer x = 0;
for(x=0 ; x<35 ; x++) {
llOwnerSay("Fibonacci("+(string)x+")="+(string)Fibonacci(x));
}
}
} |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Rust | Rust | use std::env;
// HQ9+ requires that '+' increments an accumulator, but it's inaccessible (and thus, unused).
#[allow(unused_variables)]
fn execute(code: &str) {
let mut accumulator = 0;
for c in code.chars() {
match c {
'Q' => println!("{}", code),
'H' => println!("Hello, Wor... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Scala | Scala | def hq9plus(code: String) : String = {
var out = ""
var acc = 0
def bottle(num: Int) : Unit = {
if (num > 1) {
out += num + " bottles of beer on the wall, " + num + " bottles of beer.\n"
out += "Take one down and pass it around, " + (num - 1) + " bottle"
if (n... |
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> <wh... | #Ruby | Ruby | def setup(ruleset)
ruleset.each_line.inject([]) do |rules, line|
if line =~ /^\s*#/
rules
elsif line =~ /^(.+)\s+->\s+(\.?)(.*)$/
rules << [$1, $3, $2 != ""]
else
raise "Syntax error: #{line}"
end
end
end
def morcov(ruleset, input_data)
rules = setup(ruleset)
while (matched =... |
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
| #OCaml | OCaml | exception My_Exception;;
exception Another_Exception of string;; |
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
| #Oforth | Oforth | : iwillThrowAnException "A new exception" Exception throw ;
: iwillCatch
| e |
try: e [ iwillThrowAnException ] when: [ "Exception catched :" . e .cr ]
try: e [ 1 2 over last ] when: [ "Exception catched :" . e .cr ]
"Done" println ; |
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
| #Lasso | Lasso | local(
path = file_forceroot,
ls = sys_process('/bin/ls', (:'-l', #path)),
lswait = #ls -> wait
)
'<pre>'
#ls -> read
'</pre>' |
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
| #LFE | LFE |
> (os:cmd "ls -alrt")
|
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 iterat... | #BASIC256 | BASIC256 | print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))
function factorial(n)
factorial = 1
if n > 0 then
for p = 1 to n
factorial *= p
next p
end if
end function |
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 ov... | #PowerShell | PowerShell | function pow($a, [int]$b) {
if ($b -eq -1) { return 1/$a }
if ($b -eq 0) { return 1 }
if ($b -eq 1) { return $a }
if ($b -lt 0) {
$rec = $true # reciprocal needed
$b = -$b
}
$result = $a
2..$b | ForEach-Object {
$result *= $a
}
if ($rec) {
return... |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #Smalltalk | Smalltalk | Integer extend [
fizzbuzz [
| fb |
fb := '%<Fizz|>1%<Buzz|>2' % {
self \\ 3 == 0. self \\ 5 == 0 }.
^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ]
]
]
1 to: 100 do: [ :i | i fizzbuzz displayNl ] |
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 thi... | #zkl | zkl | // http://stackoverflow.com/revisions/10733621/4
fcn postponed_sieve(){ # postponed sieve, by Will Ness
vm.yield(2); vm.yield(3); # original code David Eppstein,
vm.yield(5); vm.yield(7); # ActiveState Recipe 2002
D:=Dictionary();
ps:=Utils.Generator(postpone... |
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:... | #D | D |
program Execute_Brain;
{$APPTYPE CONSOLE}
uses
Winapi.Windows,
System.SysUtils;
const
DataSize = 1024; // Size of Data segment
MaxNest = 1000; // Maximum nesting depth of []
function Readkey: Char;
var
InputRec: TInputRecord;
NumRead: Cardinal;
... |
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.... | #Elixir | Elixir | defmodule Log do
def show(offspring,i) do
IO.puts "Generation: #{i}, Offspring: #{offspring}"
end
def found({target,i}) do
IO.puts "#{target} found in #{i} iterations"
end
end
defmodule Evolution do
# char list from A to Z; 32 is the ord value for space.
@chars [32 | Enum.to_list(?A..?Z)]
d... |
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 ... | #Lua | Lua |
--calculates the nth fibonacci number. Breaks for negative or non-integer n.
function fibs(n)
return n < 2 and n or fibs(n - 1) + fibs(n - 2)
end
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: runCode (in string: code) is func
local
var char: ch is ' ';
var integer: bottles is 0;
var integer: accumulator is 0;
begin
for ch range code do
case ch of
when {'H'}: writeln("Hello, world!");
when {'Q'}: writeln(code);
when {'9... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Sidef | Sidef | class HQ9Interpreter {
has pointer;
has accumulator;
func bob (beer) {
func what { "#{beer ? beer : 'No more'} bottle#{beer-1 ? 's' : ''} of beer" }
func where { 'on the wall' }
func drink { beer--; "Take one down, pass it around," }
while (beer.is_pos) {
[[w... |
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> <wh... | #Rust | Rust | use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct Rule {
pub pat: String,
pub rep: String,
pub terminal: bool,
}
impl Rule {
pub fn new(pat: String, rep: String, terminal: bool) -> Self {
Self { pat, rep, terminal }
}
pub fn applicable_range(&self, input: impl AsRef<str>) -... |
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> <wh... | #Scala | Scala | import scala.io.Source
object MarkovAlgorithm {
val RulePattern = """(.*?)\s+->\s+(\.?)(.*)""".r
val CommentPattern = """#.*|\s*""".r
def rule(line: String) = line match {
case CommentPattern() => None
case RulePattern(pattern, terminal, replacement) => Some(pattern, replacement, terminal == ".")
... |
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
| #Oz | Oz | raise sillyError end
raise slightlyLessSilly(data:42 reason:outOfMemory) 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
| #PARI.2FGP | PARI/GP | trap(/* specific error can be given here, or leave blank to catch all */,
"caught"
,
error("bad stuff")
) |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.