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_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Racket | Racket | class SNUSP {
has @!inst-pointer;
has @!call-stack;
has @!direction;
has @!memory;
has $!mem-pointer;
method run ($code) {
init();
my @code = pad( |$code.lines );
for @code.kv -> $r, @l {
my $index = @l.grep( /'$'/, :k );
if $index {
... |
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... | #J | J | if2=: 2 :0
'`b1 b2'=. n
m@.(b1 + 2 * b2) f.
) |
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... | #Java | Java |
public class If2 {
public static void if2(boolean firstCondition, boolean secondCondition,
Runnable bothTrue, Runnable firstTrue, Runnable secondTrue, Runnable noneTrue) {
if (firstCondition)
if (secondCondition)
bothTrue.run();
else fir... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Wren | Wren | import "/fmt" for Fmt
var ops = [ "5**3**2", "(5**3)**2", "5**(3**2)" ]
var results = [ 5.pow(3).pow(2), (5.pow(3)).pow(2), 5.pow(3.pow(2)) ]
for (i in 0...ops.count) {
System.print("%(Fmt.s(-9, ops[i])) -> %(results[i])")
} |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #zkl | zkl | println("5 ^ 3 ^ 2 = %,d".fmt((5.0).pow((3.0).pow(2))));
println("(5 ^ 3) ^ 2 = %,d".fmt((5.0).pow(3).pow(2)));
println("5 ^ (3 ^ 2) = %,d".fmt((5.0).pow((3.0).pow(2)))); |
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)
... | #REALbasic | REALbasic |
let fizzbuzz i =>
switch (i mod 3, i mod 5) {
| (0, 0) => "FizzBuzz"
| (0, _) => "Fizz"
| (_, 0) => "Buzz"
| _ => string_of_int i
};
for i in 1 to 100 {
print_endline (fizzbuzz 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 thi... | #jq | jq | # Recent versions of jq include the following definition:
# until/2 loops until cond is satisfied,
# and emits the value satisfying the condition:
def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;
def count(cond): reduce .[] as $x (0; if $x|cond then .+1 else . end); |
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 ... | #IDL | IDL | function fib,n
if n lt 3 then return,1L else return, fib(n-1)+fib(n-2)
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 |... | #Ring | Ring |
nArray = list(100)
n = 45
j = 0
for i = 1 to n
if n % i = 0 j = j + 1 nArray[j] = i ok
next
see "Factors of " + n + " = "
for i = 1 to j
see "" + nArray[i] + " "
next
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #E | E | open unsafe.console char unsafe.cell imperative
eval src = eval' src
where eval' [] = ()
eval' (x::xs) | be 'H' = h() `seq` eval' xs
| be 'Q' = q() `seq` eval' xs
| be '9' = n() `seq` eval' xs
| be '+' = p() `seq` eval' xs
... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Ela | Ela | open unsafe.console char unsafe.cell imperative
eval src = eval' src
where eval' [] = ()
eval' (x::xs) | be 'H' = h() `seq` eval' xs
| be 'Q' = q() `seq` eval' xs
| be '9' = n() `seq` eval' xs
| be '+' = p() `seq` eval' xs
... |
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... | #APL | APL | markov←{
trim←{(~(∧\∨⌽∘(∧\)∘⌽)⍵∊⎕UCS 9 32)/⍵}
rules←(~rules∊⎕UCS 10 13)⊆rules←80 ¯1 ⎕MAP ⍺
rules←('#'≠⊃¨rules)/rules
rules←{
norm←' '@(9=⎕UCS)⊢⍵
spos←⍸' -> '⍷norm
pat←trim spos↑⍵
repl←trim(spos+2)↓⍵
term←'.'=⊃repl
term pat(term↓repl)
}¨rules
apply←... |
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... | #AutoHotkey | AutoHotkey | ;---------------------------------------------------------------------------
; Markov Algorithm.ahk
; by wolf_II
;---------------------------------------------------------------------------
; interpreter for a Markov Algorithm
;---------------------------------------------------------------------------
;---------... |
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... | #Clojure | Clojure | (def U0 (ex-info "U0" {}))
(def U1 (ex-info "U1" {}))
(defn baz [x] (if (= x 0) (throw U0) (throw U1)))
(defn bar [x] (baz x))
(defn foo []
(dotimes [x 2]
(try
(bar x)
(catch clojure.lang.ExceptionInfo e
(if (= e U0)
(println "foo caught U0")
(throw e))))))
(defn -m... |
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... | #Common_Lisp | Common Lisp | (define-condition user-condition-1 (error) ())
(define-condition user-condition-2 (error) ())
(defun foo ()
(dolist (type '(user-condition-1 user-condition-2))
(handler-case
(bar type)
(user-condition-1 (c)
(format t "~&foo: Caught: ~A~%" c)))))
(defun bar (type)
(baz type))
(defun b... |
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
| #ALGOL_68 | ALGOL 68 | COMMENT
Define an general event handling mechanism on MODE OBJ:
* try to parallel pythons exception handling flexibility
END COMMENT
COMMENT
REQUIRES:
MODE OBJ # These can be a UNION of REF types #
OP OBJIS
PROVIDES:
OP ON, RAISE, RESET
PROC obj on, obj raise, obj reset
END COMMENT
# define... |
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
| #AppleScript | AppleScript | do shell script "ls" without altering line endings |
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
| #Applesoft_BASIC | Applesoft BASIC | ? CHR$(4)"CATALOG" |
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... | #Ada | Ada | function Factorial (N : Positive) return Positive is
Result : Positive := N;
Counter : Natural := N - 1;
begin
for I in reverse 1..Counter loop
Result := Result * I;
end loop;
return Result;
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 ov... | #Ela | Ela | open number
_ ^ 0 = 1
x ^ n | n > 0 = f x (n - 1) x
|else = fail "Negative exponent"
where f _ 0 y = y
f a d y = g a d
where g b i | even i = g (b * b) (i `quot` 2)
| else = f b (i - 1) (b * y)
(12 ^ 4, 12 ** 4) |
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... | #Elixir | Elixir | defmodule My do
def exp(x,y) when is_integer(x) and is_integer(y) and y>=0 do
IO.write("int> ") # debug test
exp_int(x,y)
end
def exp(x,y) when is_integer(y) do
IO.write("float> ") # debug test
exp_float(x,y)
end
def exp(x,y), do: (IO.write(" "); :math.pow(x,y))
def... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Nim | Nim | proc hailstone*(n: int): auto =
result = @[n]
var n = n
while n > 1:
if (n and 1) == 1:
n = 3 * n + 1
else:
n = n div 2
result.add n
when isMainModule:
let h = hailstone 27
assert h.len == 112 and h[0..3] == @[27,82,41,124] and h[h.high-3..h.high] == @[8,4,2,1]
var m, mi = 0
for ... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #PARI.2FGP | PARI/GP | #include <pari/pari.h>
#define HAILSTONE1 "n=1;print1(%d,\": \");apply(x->while(x!=1,if(x/2==x\\2,x/=2,x=x*3+1);n++;print1(x,\", \")),%d);print(\"(\",n,\")\n\")"
#define HAILSTONE2 "m=n=0;for(i=2,%d,h=1;apply(x->while(x!=1,if(x/2==x\\2,x/=2,x=x*3+1);h++),i);if(m<h,m=h;n=i));print(n,\": \",m)"
void hailsto... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Smalltalk | Smalltalk | FloatE nan
FloatD nan
FloatE infinity
FloatD infinity
FloatE negativeInfinity
FloatD negativeInfinity
Float zero -> 0.0
Float negativeZero -> -0.0
0.0 negated -> -0.0
0.0 negated = 0.0 -> true. "they have the same value"
0.0 negated < 0.0 -> false
0.0 negated > 0.0 -> false
1.0 isFinite -> true
FloatE infinity isFi... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Raku | Raku | class SNUSP {
has @!inst-pointer;
has @!call-stack;
has @!direction;
has @!memory;
has $!mem-pointer;
method run ($code) {
init();
my @code = pad( |$code.lines );
for @code.kv -> $r, @l {
my $index = @l.grep( /'$'/, :k );
if $index {
... |
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... | #Julia | Julia |
const CSTACK1 = Array{Bool,1}()
const CSTACK2 = Array{Bool,1}()
const CSTACK3 = Array{Bool,1}()
macro if2(condition1, condition2, alltrue)
if !(length(CSTACK1) == length(CSTACK2) == length(CSTACK3))
throw("prior if2 statement error: must have if2, elseif1, elseif2, and elseifneither")
end
ifcond... |
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... | #Kotlin | Kotlin | // version 1.0.6
data class IfBoth(val cond1: Boolean, val cond2: Boolean) {
fun elseFirst(func: () -> Unit): IfBoth {
if (cond1 && !cond2) func()
return this
}
fun elseSecond(func: () -> Unit): IfBoth {
if (cond2 && !cond1) func()
return this
}
fun elseNeither(... |
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)
... | #ReasonML | ReasonML |
let fizzbuzz i =>
switch (i mod 3, i mod 5) {
| (0, 0) => "FizzBuzz"
| (0, _) => "Fizz"
| (_, 0) => "Buzz"
| _ => string_of_int i
};
for i in 1 to 100 {
print_endline (fizzbuzz 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 thi... | #Julia | Julia | using Primes
sum = 2
currentprime = 2
for i in 2:100000
currentprime = nextprime(currentprime + 1)
sum += currentprime
end
println("The sum of the first 100,000 primes is $sum")
curprime = 1
arr = zeros(Int, 20)
for i in 1:20
curprime = nextprime(curprime + 1)
arr[i] = curprime
end
println("The firs... |
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:... | #11l | 11l | F bf(source)
V tape = DefaultDict[Int, Int]()
V cell = 0
V ptr = 0
L ptr < source.len
S source[ptr]
‘>’
cell++
‘<’
cell--
‘+’
tape[cell]++
‘-’
tape[cell]--
‘.’
:stdout.write(Char(code' tape[cell]))... |
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.... | #11l | 11l | V target = Array(‘METHINKS IT IS LIKE A WEASEL’)
V alphabet = ‘ ABCDEFGHIJLKLMNOPQRSTUVWXYZ’
V p = 0.05
V c = 100
F neg_fitness(trial)
R sum(zip(trial, :target).map((t, h) -> Int(t != h)))
F mutate(parent)
R parent.map(ch -> (I random:() < :p {random:choice(:alphabet)} E ch))
V parent = (0 .< target.len).ma... |
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 ... | #Idris | Idris | fibAnalytic : Nat -> Double
fibAnalytic n =
floor $ ((pow goldenRatio n) - (pow (-1.0/goldenRatio) n)) / sqrt(5)
where goldenRatio : Double
goldenRatio = (1.0 + sqrt(5)) / 2.0 |
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 |... | #Ruby | Ruby | class Integer
def factors() (1..self).select { |n| (self % n).zero? } end
end
p 45.factors |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Erlang | Erlang | % hq9+ Erlang implementation (JWL)
% http://www.erlang.org/
-module(hq9p).
-export([main/1]).
%% bottle helper routine
bottle(0) ->
io:format("No more bottles of beer ");
bottle(1) ->
io:format("1 bottle of beer ");
bottle(N) when N > 0 ->
io:format("~w bottles of beer ", [N]).
%% Implementation of instru... |
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... | #BBC_BASIC | BBC BASIC | PRINT FNmarkov("ruleset1.txt", "I bought a B of As from T S.")
PRINT FNmarkov("ruleset2.txt", "I bought a B of As from T S.")
PRINT FNmarkov("ruleset3.txt", "I bought a B of As W my Bgage from T S.")
PRINT FNmarkov("ruleset4.txt", "_1111*11111_")
PRINT FNmarkov("ruleset5.txt", "000000A0000... |
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... | #Bracmat | Bracmat |
markov=
{
First the patterns that describe the rules syntax.
This is a naive and not very efficient way to parse the rules, but it closely
matches the problem description, which is nice.
}
( ruleset
= >%@" " ? { Added: assume that a rule cannot start with whitespace.
The %@ say th... |
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... | #Crystal | Crystal | class U0 < Exception
end
class U1 < Exception
end
def foo
2.times do |i|
begin
bar(i)
rescue e : U0
puts "rescued #{e}"
end
end
end
def bar(i : Int32)
baz(i)
end
def baz(i : Int32)
raise U0.new("this is u0") if i == 0
raise U1.new("this is u1") if i == 1
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 rais... | #D | D | class U0 : Exception {
this() @safe pure nothrow { super("U0 error message"); }
}
class U1 : Exception {
this() @safe pure nothrow { super("U1 error message"); }
}
void foo() {
import std.stdio;
foreach (immutable i; 0 .. 2) {
try {
i.bar;
} catch (U0) {
"Fu... |
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
| #AppleScript | AppleScript | try
set num to 1 / 0
--do something that might throw an error
end try |
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
| #AutoHotkey | AutoHotkey | try
BadlyCodedFunc()
catch e
MsgBox % "Error in " e.What ", which was called at line " e.Line
BadlyCodedFunc() {
throw Exception("Fail", -1)
} |
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
| #Arturo | Arturo | print execute "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
| #AutoHotkey | AutoHotkey | Run, %comspec% /k 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... | #Agda | Agda | factorial : ℕ → ℕ
factorial zero = 1
factorial (suc n) = suc n * factorial 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... | #Erlang | Erlang |
pow(X, Y) when Y < 0 ->
1/pow(X, -Y);
pow(X, Y) when is_integer(Y) ->
pow(X, Y, 1).
pow(_, 0, B) ->
B;
pow(X, Y, B) ->
B2 = if Y rem 2 =:= 0 -> B; true -> X * B end,
pow(X * X, Y div 2, B2).
|
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Perl | Perl | package Hailstone;
sub seq {
my $x = shift;
$x == 1 ? (1) : ($x & 1)? ($x, seq($x * 3 + 1))
: ($x, seq($x / 2))
}
my %cache = (1 => 1);
sub len {
my $x = shift;
$cache{$x} //= 1 + (
$x & 1 ? len($x * 3 + 1)
: len($x / 2))
}
unless (caller) {
for (1 .. 100_000) {
my $l = len($_);
(... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Phix | Phix | --global (if you want to be able to call this from test.exw)
function hailstone(atom n)
sequence s = {n}
while n!=1 do
if remainder(n,2)=0 then
n /= 2
else
n = 3*n+1
end if
s &= n
end while
return s
end function
global function hailstone_count(atom n... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Stata | Stata | . display %21x .
+1.0000000000000X+3ff
. display %21x .a
+1.0010000000000X+3ff
. display %21x .z
+1.01a0000000000X+3ff
. display %21x c(maxdouble)
+1.fffffffffffffX+3fe |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Swift | Swift | let negInf = -1.0 / 0.0
let inf = 1.0 / 0.0 //also Double.infinity
let nan = 0.0 / 0.0 //also Double.NaN
let negZero = -2.0 / inf
println("Negative inf: \(negInf)")
println("Positive inf: \(inf)")
println("NaN: \(nan)")
println("Negative 0: \(negZero)")
println("inf + -inf: \(inf + negInf)")
println("0 * NaN: \(0 * n... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Ruby | Ruby | $ include "seed7_05.s7i";
const proc: snusp (in string: sourceCode, in integer: memSize, inout file: input, inout file: output) is func
local
var array string: instructions is 0 times "";
var array char: memory is 0 times ' ';
var integer: dataPointer is 1;
var integer: instrPtrRow is 0;
var int... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: snusp (in string: sourceCode, in integer: memSize, inout file: input, inout file: output) is func
local
var array string: instructions is 0 times "";
var array char: memory is 0 times ' ';
var integer: dataPointer is 1;
var integer: instrPtrRow is 0;
var int... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Tcl | Tcl | import "io" for Stdin
// 'raw' is a multi-line string
var snusp = Fn.new { |dlen, raw|
var ds = List.filled(dlen, 0) // data store
var dp = 0 // data pointer
// remove leading \n if it's there
if (raw[0] == "\n") raw = raw[1..-1]
// make 2 dimensional instruction store & declare instruction po... |
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... | #Lua | Lua | -- Extend your language, in Lua, 6/17/2020 db
-- not to be taken seriously, ridiculous, impractical, esoteric, obscure, arcane ... but it works
-------------------
-- IMPLEMENTATION:
-------------------
function if2(cond1, cond2)
return function(code)
code = code:gsub("then2", "[3]=load[[")
code = code:gs... |
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)
... | #REBOL | REBOL | rebol [
Title: "FizzBuzz"
URL: http://rosettacode.org/wiki/FizzBuzz
]
; Concatenative. Note use of 'case/all' construct to evaluate all
; conditions. I use 'copy' to allocate a new string each time through
; the loop -- otherwise 'x' would get very long...
repeat i 100 [
x: copy ""
case/all [
0 = mod i 3 [app... |
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... | #Kotlin | Kotlin | fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun generatePrime... |
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:... | #68000_Assembly | 68000 Assembly | ;
; Brainfuck interpreter by Thorham
;
; 68000+ AmigaOs2+
;
; Cell size is a byte
;
incdir "asminc:"
include "dos/dosextens.i"
include "lvo/lvos.i"
execBase equ 4
start
; parse command line parameter
move.l a0,fileName
move.b (a0)+,d0
beq exit ; no parameter
cmp.b #'"',... |
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.... | #8080_Assembly | 8080 Assembly | MRATE: equ 26 ; Chance of mutation (MRATE/256)
COPIES: equ 100 ; Amount of copies to make
fname1: equ 5Dh ; First filename on command line (used for RNG seed)
fname2: equ 6Dh ; Second filename (also used for RNG seed)
org 100h
;;; Make random seed from the two CP/M 'filenames'
lxi b,rnddat
lxi h,fname1
xra a
call... |
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 ... | #J | J | fibN=: (-&2 +&$: -&1)^:(1&<) M."0 |
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 |... | #Run_BASIC | Run BASIC | PRINT "Factors of 45 are ";factorlist$(45)
PRINT "Factors of 12345 are "; factorlist$(12345)
END
function factorlist$(f)
DIM L(100)
FOR i = 1 TO SQR(f)
IF (f MOD i) = 0 THEN
L(c) = i
c = c + 1
IF (f <> i^2) THEN
L(c) = (f / i)
c = c + 1
END IF
END IF
NEXT i
s = 1
while s = 1
s = 0
for ... |
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 |... | #Rust | Rust | fn main() {
assert_eq!(vec![1, 2, 4, 5, 10, 10, 20, 25, 50, 100], factor(100)); // asserts that two expressions are equal to each other
assert_eq!(vec![1, 101], factor(101));
}
fn factor(num: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new(); // creates a new vector for the factors of the number... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Factor | Factor | USING: combinators command-line formatting interpolate io kernel
math math.ranges multiline namespaces sequences ;
IN: rosetta-code.hq9+
STRING: verse
${3} bottle${1} of beer on the wall
${3} bottle${1} of beer
Take one down, pass it around
${2} bottle${0} of beer on the wall
;
: bottles ( -- )
99 1 [a,b]
[... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Forth | Forth | variable accumulator
: H cr ." Hello, world!" ;
: Q cr 2dup type ;
: 9 99 verses ; \ http://rosettacode.org/wiki/99_Bottles_of_Beer#Forth
: + 1 accumulator +! ;
: hq9+ ( "code" -- )
parse-word 2dup bounds ?do
i 1 [ get-current literal ] search-wordlist
if execute else true abort" invalid HQ9+ instruction"
... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
typedef struct { char * s; size_t alloc_len; } string;
typedef struct {
char *pat, *repl;
int terminate;
} rule_t;
typedef struct {
int n;
... |
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... | #Delphi | Delphi | program ExceptionsInNestedCall;
{$APPTYPE CONSOLE}
uses SysUtils;
type
U0 = class(Exception)
end;
U1 = class(Exception)
end;
procedure Baz(i: Integer);
begin
if i = 0 then
raise U0.Create('U0 Error message')
else
raise U1.Create('U1 Error message');
end;
procedure Bar(i: Integer);
begin
... |
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
| #BBC_BASIC | BBC BASIC | ON ERROR PROCerror(ERR, REPORT$) : END
ERROR 100, "User-generated exception"
END
DEF PROCerror(er%, rpt$)
PRINT "Exception occurred"
PRINT "Error number was " ; er%
PRINT "Error string was " rpt$
ENDPROC |
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
| #blz | blz |
try
1 / 0 # Throw an exception
print("unreachable code")
catch
print("An error occured!")
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
| #AutoIt | AutoIt | Run(@ComSpec & " /c " & 'pause', "", @SW_HIDE) |
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
| #AWK | AWK | BEGIN {
system("ls") # Unix
#system("dir") # DOS/MS-Windows
} |
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... | #Aime | Aime | integer
factorial(integer n)
{
integer i, result;
result = 1;
i = 1;
while (i < n) {
i += 1;
result *= i;
}
return result;
} |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #ERRE | ERRE | PROGRAM POWER
PROCEDURE POWER(A,B->POW) ! this routine handles only *INTEGER* powers
LOCAL FLAG%
IF B<0 THEN B=-B FLAG%=TRUE
POW=1
FOR X=1 TO B DO
POW=POW*A
END FOR
IF FLAG% THEN POW=1/POW
END PROCEDURE
BEGIN
POWER(11,-2->POW) PRINT(POW)
POWER(π,3->POW) PRINT(POW)
END PROGRAM |
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... | #F.23 | F# |
//Integer Exponentiation, more interesting anyway than repeated multiplication. Nigel Galloway, October 12th., 2018
let rec myExp n g=match g with
|0 ->1
|g when g%2=1 ->n*(myExp n (g-1))
|_ ->let p=myExp n (g/2) in p*p
printfn "%d" (myExp ... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(de hailstone (N)
(make
(until (= 1 (link N))
(setq N
(if (bit? 1 N)
(inc (* N 3))
(/ N 2) ) ) ) ) )
(de hailtest ()
(let L (hailstone 27)
(test 112 (length L))
(test (27 82 41 124) (head 4 L))
... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Pike | Pike | #!/usr/bin/env pike
int next(int n)
{
if (n==1)
return 0;
if (n%2)
return 3*n+1;
else
return n/2;
}
array(int) hailstone(int n)
{
array seq = ({ n });
while (n=next(n))
seq += ({ n });
return seq;
}
void main()
{
array(int) two = hailstone(27);
if (e... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Tcl | Tcl | % package require Tcl 8.5
8.5.2
% expr inf+1
Inf
% set inf_val [expr {1.0 / 0.0}]
Inf
% set neginf_val [expr {-1.0 / 0.0}]
-Inf
% set negzero_val [expr {1.0 / $neginf_val}]
-0.0
% expr {0.0 / 0.0}
domain error: argument not in valid range
% expr nan
domain error: argument not in valid range
% expr {1/-inf}
-0.0 |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Wren | Wren | var inf = 1/0
var negInf = -1/0
var nan = 0/0
var negZero = -0
System.print([inf, negInf, nan, negZero])
System.print([inf + inf, negInf + inf, nan * nan, negZero == 0])
System.print([inf/inf, negInf/2, nan + inf, negZero/0])
|
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Wren | Wren | import "io" for Stdin
// 'raw' is a multi-line string
var snusp = Fn.new { |dlen, raw|
var ds = List.filled(dlen, 0) // data store
var dp = 0 // data pointer
// remove leading \n if it's there
if (raw[0] == "\n") raw = raw[1..-1]
// make 2 dimensional instruction store & declare instruction po... |
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... | #Lambdatalk | Lambdatalk |
{macro \{if2 (true|false|\{[^{}]*\}) (true|false|\{[^{}]*\})\}
to {if {and $1 $2}
then both are true
else {if {and $1 {not $2}}
then the first is true
else {if {and {not $1} $2}
then the second is true
else neither are true}}}}
{if2 true true} -> both are true
{if2 ... |
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)
... | #Red | Red | Red ["FizzBuzz"]
repeat i 100 [
print case [
i % 15 = 0 ["FizzBuzz"]
i % 5 = 0 ["Buzz"]
i % 3 = 0 ["Fizz"]
true [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 thi... | #Lua | Lua | local primegen = {
count_limit = 2,
value_limit = 3,
primelist = { 2, 3 },
nextgenvalue = 5,
nextgendelta = 2,
tbd = function(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
local limit = math.sqrt(n)
for f = 5, limit, 6 do
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:... | #8080_Assembly | 8080 Assembly | ;;; CP/M Brainfuck compiler/interpreter, with a few optimizations
getch: equ 1 ; Read character from console
putch: equ 2 ; Print character to console
puts: equ 9 ; Print string to console
fopen: equ 15 ; Open file
fread: equ 20 ; Read from file
dmaoff: equ 26 ; Set DMA address
fcb: equ 5Ch ; FCB for first command li... |
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.... | #8086_Assembly | 8086 Assembly | bits 16
cpu 8086
MRATE: equ 26 ; Mutation rate (MRATE/256)
COPIES: equ 100 ; Amount of copies to make
gettim: equ 02Ch ; MS-DOS get time function
pstr: equ 9 ; MS-DOS print string
section .text
org 100h
;;; Use MS-DOS time to set random seed
mov ah,gettim
int 21h
mov [rnddat],cx
mov [rnddat+2],dx
;;; Make ... |
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 ... | #Java | Java | public static long itFibN(int n)
{
if (n < 2)
return n;
long ans = 0;
long n1 = 0;
long n2 = 1;
for(n--; n > 0; n--)
{
ans = n1 + n2;
n1 = n2;
n2 = ans;
}
return ans;
} |
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 |... | #Sather | Sather | class MAIN is
factors!(n :INT):INT is
yield 1;
loop i ::= 2.upto!( n.flt.sqrt.int );
if n%i = 0 then
yield i;
if (i*i) /= n then
yield n / i;
end;
end;
end;
yield n;
end;
main is
a :ARRAY{INT} := |3135, 45, 64, 53, 45, 81|;
loop l ::= a.elt... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Fortran | Fortran | "bottle" // IF (B.NE.1) THEN "s" FI // " of beer" |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #FreeBASIC | FreeBASIC |
' Intérprete de HQ9+
' FB 1.05.0 Win64
'
Dim Shared codigo As String: codigo = ""
Function HQ9plus(codigo As String) As String
Dim As Byte botellas, cont
Dim acumulador As Uinteger = 0
Dim HQ9plus1 As String
For cont = 1 To Len(codigo)
Select Case Ucase(Mid(codigo, cont, 1))
Case "... |
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... | #C.2B.2B | C++ |
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
struct rule
{
std::string pattern;
std::string replacement;
bool terminal;
rule(std::string pat, std::string rep, bool term):
pattern(pat),
replacement(rep),
terminal(term)
{
}
};
std::string cons... |
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... | #DWScript | DWScript | type Exception1 = class (Exception) end;
type Exception2 = class (Exception) end;
procedure Baz(i : Integer);
begin
if i=0 then
raise new Exception1('Error message 1')
else raise new Exception2('Error message 2');
end;
procedure Bar(i : Integer);
begin
Baz(i);
end;
procedure Foo;
var
i : Integer... |
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... | #Dyalect | Dyalect | var bazCallCount = 0
func baz() {
bazCallCount += 1
if bazCallCount == 1 {
throw @BazCall1()
} else if bazCallCount == 2 {
throw @BazCall2()
}
}
func bar() {
baz()
}
func foo() {
var calls = 2
while calls > 0 {
try {
bar()
} catch {
... |
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
| #Bracmat | Bracmat | ( ( MyFunction
= someText XMLstuff
. ( get$!arg:?someText
& get$("CorporateData.xml",X,ML):?XMLstuff
| out
$ ( str
$ ( "Something went wrong when reading your file \""
!arg
"\". Or was it the Corporate Data? Hard to say. Any... |
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
| #C | C | #include <setjmp.h>
enum { MY_EXCEPTION = 1 }; /* any non-zero number */
jmp_buf env;
void foo()
{
longjmp(env, MY_EXCEPTION); /* throw MY_EXCEPTION */
}
void call_foo()
{
switch (setjmp(env)) {
case 0: /* try */
foo();
break;
case MY_EXCEPTION: /* catch MY_EXCEPTION... |
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
| #BASIC | BASIC | SHELL "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
| #BASIC256 | BASIC256 | system "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 iterat... | #ALGOL_60 | ALGOL 60 | begin
comment factorial - algol 60;
integer procedure factorial(n); integer n;
begin
integer i,fact;
fact:=1;
for i:=2 step 1 until n do
fact:=fact*i;
factorial:=fact
end;
integer i;
for i:=1 step 1 until 10 do outinteger(1,factorial(i));
outstring(1,"\n")
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 ov... | #Factor | Factor | : pow ( f n -- f' )
dup 0 < [ abs pow recip ]
[ [ 1 ] 2dip swap [ * ] curry times ] if ; |
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... | #Forth | Forth | : ** ( n m -- n^m )
1 swap 0 ?do over * loop nip ; |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Python | Python | def hailstone(n):
seq = [n]
while n>1:
n = 3*n + 1 if n & 1 else n//2
seq.append(n)
return seq
if __name__ == '__main__':
h = hailstone(27)
assert len(h)==112 and h[:4]==[27, 82, 41, 124] and h[-4:]==[8, 4, 2, 1]
print("Maximum length %i was found for hailstone(%i) for numbers ... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Racket | Racket |
#lang racket
(provide hailstone)
(define hailstone
(let ([t (make-hasheq)])
(hash-set! t 1 '(1))
(λ(n) (hash-ref! t n
(λ() (cons n (hailstone (if (even? n) (/ n 2) (+ (* 3 n) 1)))))))))
(module+ main
(define h27 (hailstone 27))
(printf "h(27) = ~s, ~s items\n"
`(,@(take h27 4) ... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Raku | Raku | module Hailstone {
our sub hailstone($n) is export {
$n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1
}
}
sub MAIN {
say "hailstone(27) = {.[^4]} [...] {.[*-4 .. *-1]}" given Hailstone::hailstone 27;
} |
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... | #langur | langur | given .x nxor, .y nxor {
case true: ... # both true
case true, false: ... # first true, second false
case false, true: ... # first false, second true
default: ... # both false
} |
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... | #Lasso | Lasso | // Create a type to handle the captures
define if2 => type {
data private a, private b
public oncreate(a,b) => {
.a = #a
.b = #b
thread_var_push(.type,self)
handle => { thread_var_pop(.type)}
return givenblock()
}
public ifboth => .a && .b ? givenblock()
pub... |
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)
... | #Retro | Retro | : fizz? ( s-f ) 3 mod 0 = ;
: buzz? ( s-f ) 5 mod 0 = ;
: num? ( s-f ) dup fizz? swap buzz? or 0 = ;
: ?fizz ( s- ) fizz? [ "Fizz" puts ] ifTrue ;
: ?buzz ( s- ) buzz? [ "Buzz" puts ] ifTrue ;
: ?num ( s- ) num? &putn &drop if ;
: fizzbuzz ( s- ) dup ?fizz dup ?buzz dup ?num space ;
: all (... |
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.