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/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... | #Lingo | Lingo | -- As for built-in power() function:
-- base can be either integer or float; returns float.
on pow (base, exp)
if exp=0 then return 1.0
else if exp<0 then
exp = -exp
base = 1.0/base
end if
res = float(base)
repeat with i = 2 to exp
res = res*base
end repeat
return res
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... | #Logo | Logo | to int_power :n :m
if equal? 0 :m [output 1]
if equal? 0 modulo :m 2 [output int_power :n*:n :m/2]
output :n * int_power :n :m-1
end |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #Python | Python | a, b = 1, 0
if (c1 := a == 1) and (c2 := b == 3):
print('a = 1 and b = 3')
elif c1:
print('a = 1 and b <> 3')
elif c2:
print('a <> 1 and b = 3')
else:
print('a <> 1 and b <> 3') |
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)
... | #SAS | SAS | data _null_;
do i=1 to 100;
if mod(i,15)=0 then put "FizzBuzz";
else if mod(i,5)=0 then put "Buzz";
else if mod(i,3)=0 then put "Fizz";
else put i;
end;
run; |
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... | #Python | Python | islice(count(7), 0, None, 2) |
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:... | #Axe | Axe | Lbl BF
r₁→P
r₂→I
L₁→D
Fill(D,768,0)
While {P}
{P}→C
If C='+'
{D}++
ElseIf C='-'
{D}--
ElseIf C='>'
D++
ElseIf C='<'
D--
ElseIf C='.'
Disp {D}▶Char
ElseIf C=','
{I}→{D}
I++
ElseIf C='['?{D}=0
NEXT(P)→P
ElseIf C=']'
PREV(P)→P
End
P++
End
Return
Lbl NEXT
r₁++
1→S
While S
If {r₁}='['
S++... |
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.... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char target[] = "METHINKS IT IS LIKE A WEASEL";
const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
#define CHOICE (sizeof(tbl) - 1)
#define MUTATE 15
#define COPIES 30
/* returns random integer from 0 to n - 1 */
int irand(int n)
{
int r, rand_max =... |
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 ... | #lambdatalk | lambdatalk |
1) basic version
{def fib1
{lambda {:n}
{if {< :n 3}
then 1
else {+ {fib1 {- :n 1}} {fib1 {- :n 2}}} }}}
{fib1 16} -> 987 (CPU ~ 16ms)
{fib1 30} = 832040 (CPU > 12000ms)
2) tail-recursive version
{def fib2
{def fib2.r
{lambda {:a :b :i}
{if {< :i 1}
then :a
else {fib2.r :b {+ :a :b} ... |
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 |... | #Wortel | Wortel | @let {
factors1 &n !-\%%n @to n
factors_tacit @(\\%% !- @to)
[[
!factors1 10
!factors_tacit 100
!factors1 720
]]
} |
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 |... | #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
var a = [11, 21, 32, 45, 67, 96, 159, 723, 1024, 5673, 12345, 32767, 123459, 999997]
System.print("The factors of the following numbers are:")
for (e in a) System.print("%(Fmt.d(6, e)) => %(Int.divisors(e))") |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | hq9plus[program_] :=
Module[{accumulator = 0, bottle},
bottle[n_] :=
ToString[n] <> If[n == 1, " bottle", " bottles"] <> " of beer";
Do[Switch[chr, "H", Print@"hello, world", "Q", Print@program, "9",
Print@StringJoin[
Table[bottle[n] <> " on the wall\n" <> bottle[n] <>
"\ntake one down, ... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #MiniScript | MiniScript | code = input("Enter HQ9+ program: ")
sing = function()
for i in range(99,2)
print i + " bottles of beer on the wall, " + i + " bottles of beer"
print "Take one down, pass it around, " + (i-1) + " bottle" + "s"*(i>2) + " of beer on the wall"
end for
print "1 bottle of beer on the wall, 1 bo... |
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... | #JavaScript | JavaScript | /**
* Take a ruleset and return a function which takes a string to which the rules
* should be applied.
* @param {string} ruleSet
* @returns {function(string): string}
*/
const markov = ruleSet => {
/**
* Split a string at an index
* @param {string} s The string to split
* @param {number} i The index ... |
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... | #Maple | Maple | num_times:=0:
baz := proc()
global num_times := num_times + 1;
error `if`(num_times <= 1, "U0", "U1");
end proc:
bar:=proc()
baz();
end proc;
foo:=proc()
local i;
for i from 0 to 1 do
bar();
end do;
end 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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | foo[] := Catch[ bar[1]; bar[2]; ]
bar[i_] := baz[i];
baz[i_] := Switch[i,
1, Throw["Exception U0 in baz"];,
2, Throw["Exception U1 in baz"];] |
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... | #MATLAB_.2F_Octave | MATLAB / Octave | function exceptionsCatchNestedCall()
function foo()
try
bar(1);
bar(2);
catch
disp(lasterror);
rethrow(lasterror);
end
end
function bar(i)
baz(i);
end
function baz(i)
switch i
case 1
... |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Go | Go | package main
import "fmt"
func foo() int {
fmt.Println("let's foo...")
defer func() {
if e := recover(); e != nil {
fmt.Println("Recovered from", e)
}
}()
var a []int
a[12] = 0
fmt.Println("there's no point in going on.")
panic("never reached")
panic(fmt.Scan) // Can use any value, here a function!
}... |
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
| #Haskell | Haskell | do {- ... -}
throwIO SomeException |
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
| #E | E | def ls := makeCommand("ls")
ls("-l")
def [results, _, _] := ls.exec(["-l"])
when (results) -> {
def [exitCode, out, err] := results
print(out)
} catch problem {
print(`failed to execute ls: $problem`)
} |
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
| #Emacs_Lisp | Emacs Lisp | (shell-command "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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program factorial.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMe... |
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... | #Lua | Lua | number = {}
function number.pow( a, b )
local ret = 1
if b >= 0 then
for i = 1, b do
ret = ret * a.val
end
else
for i = b, -1 do
ret = ret / a.val
end
end
return ret
end
function number.New( v )
local num = { val = v }
local mt ... |
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... | #Quackery | Quackery | ( --------------------- version #1 --------------------- )
[ not swap not 1 << |
]'[ swap peek do ] is if2.1 ( b b --> )
[ if2.1
[ [ say "true and true" ]
[ say "true and false" ]
[ say "false and true" ]
[ say "false and false" ] ]
cr ] ... |
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... | #R | R |
if2 <- function(condition1, condition2, both_true, first_true, second_true, both_false)
{
expr <- if(condition1)
{
if(condition2) both_true else first_true
} else if(condition2) second_true else both_false
eval(expr)
}
|
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)
... | #Sather | Sather | class MAIN is
main is
loop i ::= 1.upto!(100);
s:STR := "";
if i % 3 = 0 then s := "Fizz"; end;
if i % 5 = 0 then s := s + "Buzz"; end;
if s.length > 0 then
#OUT + s + "\n";
else
#OUT + i + "\n";
end;
end;
end;
end; |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi... | #Racket | Racket | #lang racket
;; Using the prime functions from:
(require math/number-theory)
(displayln "Show the first twenty primes.")
(next-primes 1 20)
(displayln "Show the primes between 100 and 150.")
;; Note that in each of the in-range filters I "add1" to the stop value, so that (in this case) 150 is
;; considered. I'm pre... |
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:... | #BASIC | BASIC | 0 ON NOT T GOTO 20 : FOR A = T TO L : B = PEEK(S + P) : ON C%(ASC(MID$(C$, A, T))) GOSUB 1, 2, 3, 4, 5, 8, 6, 7 : NEXT A : END
1 P = P + T : ON P < E GOTO 11 : O = 1E99
2 P = P - T : ON P > M GOTO 11 : O = 1E99
3 B = B + T : B = B - (B > U) * B : GOTO 9
4 B = B - T : B = B - (B < 0) * (B - U) : GOTO 9
5 PRINT CHR$(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.... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
static class Program {
static Random Rng = new Random((int)DateTime.Now.Ticks);
static char NextCharacter(this Random self) {
const string AllowedChars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
return AllowedChars[self.Next() % Allowe... |
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 ... | #Lang5 | Lang5 | [] '__A set : dip swap __A swap 2 compress collapse '__A set execute
__A -1 extract nip ; : nip swap drop ; : tuck swap over ;
: -rot rot rot ; : 0= 0 == ; : 1+ 1 + ; : 1- 1 - ; : sum '+ reduce ;
: bi 'keep dip execute ; : keep over 'execute dip ;
: fib dup 1 > if dup 1- fib swap 2 - fib + then ;
: fib dup 1 ... |
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 |... | #X86_Assembly | X86 Assembly |
section .bss
factorArr resd 250 ;big buffer against seg fault
section .text
global _main
_main:
mov ebp, esp; for correct debugging
mov eax, 0x7ffffffe ;number of which we want to know the factors, max num this program works with
mov ebx, eax ;save eax
mov ecx, 1 ;n, factor we test for
mov ... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Nanoquery | Nanoquery | import Nanoquery.IO
// a function to handle fatal errors
def fatal_error(errtext)
println "%" + errtext
println "usage: " + args[1] + " [filename.cp]"
exit(1)
end
// a function to perform '99 bottles of beer'
def bottles(n)
for bottles in range(n, 1, -1)
bottlestr = ""
if bottles = 1
bottlestr = "bottl... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #NetRexx | NetRexx |
var program = "9hHqQ+"
var i = 0
proc bottle(n: int): string =
case n
of 0:
result = "No more bottles"
of 1:
result = "1 bottle"
else:
result = $n & " bottles"
proc ninetyNineBottles =
for n in countdown(99, 1):
echo bottle(n), " bottle of beer on the wall"
echo bottle(n), " bottle o... |
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... | #jq | jq | jq -nrR --rawfile markov_rules markov_rules.txt -f program.jq markov_tests.txt
|
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... | #Julia | Julia | module MarkovAlgos
struct MarkovRule{F,T}
patt::F
repl::T
term::Bool
end
isterminating(r::MarkovRule) = r.term
Base.show(io::IO, rule::MarkovRule) =
print(io, rule.patt, " → ", isterminating(rule) ? "." : "", rule.repl)
function Base.convert(::Type{MarkovRule}, s::AbstractString)
rmatch = match(... |
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... | #Nemerle | Nemerle | using System;
using System.Console;
namespace NestedExceptions
{
public class U0 : Exception
{
public this() {base()}
}
public class U1 : Exception
{
public this() {base()}
}
module NestedExceptions
{
Foo () : void
{
mutable call = 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... | #Nim | Nim | type U0 = object of Exception
type U1 = object of Exception
proc baz(i) =
if i > 0: raise newException(U1, "Some error")
else: raise newException(U0, "Another error")
proc bar(i) =
baz(i)
proc foo() =
for i in 0..1:
try:
bar(i)
except U0:
echo "Function foo caught exception U0"
foo() |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to rais... | #Objective-C | Objective-C | @interface U0 : NSObject { }
@end
@interface U1 : NSObject { }
@end
@implementation U0
@end
@implementation U1
@end
void foo();
void bar(int i);
void baz(int i);
void foo() {
for (int i = 0; i <= 1; i++) {
@try {
bar(i);
} @catch (U0 *e) {
NSLog(@"Function foo caught exception U0");
}
}
... |
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
| #HolyC | HolyC | try {
U8 *err = 'Error';
throw(err); // throw exception
} catch {
if (err == 'Error')
Print("Raised 'Error'");
PutExcept; // print the exception and stack trace
} |
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
| #Icon_and_Unicon | Icon and Unicon | import Exceptions
procedure main(A)
every i := !A do {
case Try().call{ write(g(i)) } of {
Try().catch(): {
x := Try().getException()
write(x.getMessage(), ":\n", x.getLocation())
}
}
}
end
procedure g(i)
if numeric(i) =... |
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
| #Erlang | Erlang | os:cmd("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
| #ERRE | ERRE | SHELL("DIR/W") |
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
| #Euphoria | Euphoria | -- system --
-- the simplest way --
-- system spawns a new shell so I/O redirection is possible --
system( "dir /w c:\temp\ " ) -- Microsoft --
system( "/bin/ls -l /tmp" ) -- Linux BSD OSX --
----
-- system_exec() -- ... |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #ArnoldC | ArnoldC | LISTEN TO ME VERY CAREFULLY factorial
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
GIVE THESE PEOPLE AIR
BECAUSE I'M GOING TO SAY PLEASE n
BULLS***
I'LL BE BACK 1
YOU HAVE NO RESPECT FOR LOGIC
HEY CHRISTMAS TREE product
YOU SET US UP @NO PROBLEMO
STICK AROUND n
GET TO THE CHOPPER product
HERE IS MY INVITATION p... |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #Lucid | Lucid | pow(n,x)
k = n fby k div 2;
p = x fby p*p;
y =1 fby if even(k) then y else y*p;
result y asa k eq 0;
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... | #M2000_Interpreter | M2000 Interpreter |
Module Exponentiation {
\\ a variable can be any type except a string (no $ in name)
\\ variable b is long type.
\\ by default we pass by value arguments to a function
\\ to pass by reference we have to use & before name,
\\ in the signature and in the call
function pow(a, b as long) {
p=a-a ' make p same ... |
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... | #Racket | Racket |
#lang racket
;; define a new syntax
(define-syntax-rule
;; this is the new syntax we want, in sexpr syntax:
(if2 condition1isTrue condition2isTrue
bothConditionsAreTrue
firstConditionIsTrue
secondConditionIsTrue
noConditionIsTrue)
;; and this is the syntax that implements it:
(if c... |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #Raku | Raku | my &if2 = -> \a, \b, &x { my @*IF2 = ?a,?b; x }
my &if-both = -> &x { x if @*IF2 eq (True,True) }
my &if-first = -> &x { x if @*IF2 eq (True,False) }
my &if-second = -> &x { x if @*IF2 eq (False,True) }
my &if-neither = -> &x { x if @*IF2 eq (False,False)}
sub test ($a,$b) {
$_ = "G"; # Demo co... |
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)
... | #Scala | Scala | object FizzBuzz extends App {
1 to 100 foreach { n =>
println((n % 3, n % 5) match {
case (0, 0) => "FizzBuzz"
case (0, _) => "Fizz"
case (_, 0) => "Buzz"
case _ => n
})
}
} |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi... | #Raku | Raku | my @primes = lazy gather for 1 .. * { .take if .is-prime }
say "The first twenty primes:\n ", "[{@primes[^20].fmt("%d", ', ')}]";
say "The primes between 100 and 150:\n ", "[{@primes.&between(100, 150).fmt("%d", ', ')}]";
say "The number of primes between 7,700 and 8,000:\n ", +@primes.&between(7700, 8000);
say... |
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:... | #BBC_BASIC | BBC BASIC | bf$ = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>->+>>+[<]<-]>>.>" + \
\ ">---.+++++++..+++.>.<<-.>.+++.------.--------.>+.>++.+++."
PROCbrainfuck(bf$)
END
DEF PROCbrainfuck(b$)
LOCAL B%, K%, M%, P%
DIM M% LOCAL 65535
B% = 1 : REM pointer to string
K% = 0 : REM bra... |
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.... | #C.2B.2B | C++ | #include <string>
#include <cstdlib>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
#include <ctime>
std::string allowed_chars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// class selection contains the fitness function, encapsulates the
// target string and allows access to it's length. The cla... |
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 ... | #langur | langur | val .fibonacci = f if(.x < 2: .x ; self(.x - 1) + self(.x - 2))
writeln map .fibonacci, series 2..20 |
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 |... | #XPL0 | XPL0 | include c:\cxpl\codes;
int N0, N, F;
[N0:= 1;
repeat IntOut(0, N0); Text(0, " = ");
F:= 2; N:= N0;
repeat if rem(N/F) = 0 then
[if N # N0 then Text(0, " * ");
IntOut(0, F);
N:= N/F;
]
... |
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 |... | #Yabasic | Yabasic |
sub printFactors(n)
if n < 1 then return 0 : fi
print n, " =>",
for i = 1 to n / 2
if mod(n, i) = 0 then print i, " "; : fi
next i
print n
end sub
printFactors(11)
printFactors(21)
printFactors(32)
printFactors(45)
printFactors(67)
printFactors(96)
print
end
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Nim | Nim |
var program = "9hHqQ+"
var i = 0
proc bottle(n: int): string =
case n
of 0:
result = "No more bottles"
of 1:
result = "1 bottle"
else:
result = $n & " bottles"
proc ninetyNineBottles =
for n in countdown(99, 1):
echo bottle(n), " bottle of beer on the wall"
echo bottle(n), " bottle o... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #NS-HUBASIC | NS-HUBASIC | 10 INPUT "INPUT HQ9+ CODE: ",I$
20 B$="S"
30 W$=" ON THE WALL"
40 FOR I=1 TO LEN(I$)
50 C$=MID$(I$,I,1)
60 IF C$="H" THEN PRINT "HELLO, WORLD!"
70 IF C$="Q" THEN PRINT I$
80 A=A+(C$="+")
90 IF C$<>"9" GOTO 200
100 FOR B=99 TO 1 STEP -1
110 IF B=1 THEN B$=""
120 PRINT B " BOTTLE"B$" OF BEER" W$
130 PRINT B " BOTTLE"B$" ... |
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... | #Kotlin | Kotlin | // version 1.1.51
import java.io.File
import java.util.regex.Pattern
/* rulesets assumed to be separated by a blank line in file */
fun readRules(path: String): List<List<String>> {
val ls = System.lineSeparator()
return File(path).readText().split("$ls$ls").map { it.split(ls) }
}
/* tests assumed to be o... |
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... | #OCaml | OCaml | exception U0
exception U1
let baz i =
raise (if i = 0 then U0 else U1)
let bar i = baz i (* Nest those calls *)
let foo () =
for i = 0 to 1 do
try
bar i
with U0 ->
print_endline "Function foo caught exception U0"
done
let () = 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... | #Oforth | Oforth | Exception Class new: U0
Exception Class new: U1
: baz ifZero: [ "First call" U0 throw ] else: [ "Second call" U1 throw ] ;
: bar baz ;
: foo
| e |
try: e [ 0 bar ] when: [ e isKindOf(U0) ifTrue: [ "Catched" .cr ] else: [ e throw ] ]
try: e [ 1 bar ] when: [ e isKindOf(U0) ifTrue: [ "Catched" .cr ] else: [ e... |
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
| #J | J | pickyPicky =: verb define
if. y-:'bad argument' do.
throw.
else.
'thanks!'
end.
)
tryThis =: verb define
try.
pickyPicky y
catcht.
'Uh oh!'
end.
)
tryThis 'bad argument'
Uh oh! |
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
| #Java | Java | //Checked exception
public class MyException extends Exception {
//Put specific info in here
}
//Unchecked exception
public class MyRuntimeException extends RuntimeException {} |
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
| #F.23 | F# | System.Diagnostics.Process.Start("cmd", "/c 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
| #Factor | Factor | "ls" run-process wait-for-process |
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
| #Fantom | Fantom |
class Main
{
public static Void main ()
{
p := Process (["ls"])
p.run
}
}
|
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... | #Arturo | Arturo | factorial: $[n][
if? n>0 [n * factorial n-1]
else [1]
] |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #M4 | M4 | define(`power',`ifelse($2,0,1,`eval($1*$0($1,decr($2)))')')
power(2,10) |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | exponentiation[x_,y_Integer]:=Which[y>0,Times@@ConstantArray[x,y],y==0,1,y<0,1/exponentiation[x,-y]]
CirclePlus[x_,y_Integer]:=exponentiation[x,y] |
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... | #REXX | REXX | if2( some-expression-that-results-in-a-boolean-value, some-other-expression-that-results-in-a-boolean-value)
/*this part is a REXX comment*/ /*could be a DO structure.*/
select /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/ /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
when if.11 /*{condition 1 &... |
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... | #Ring | Ring |
# Project : Extend your language
see "a = 1, b = 1 => "
test(1, 1)
see "a = 1, b = 0 => "
test(1, 0)
see "a = 0, b = 1 => "
test(0, 1)
see "a = 0, b = 0 => "
test(0, 0)
see nl
func test(a,b)
if a > 0 and b > 0
see "both positive"
but a > 0
see "first positive"
but b >... |
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)
... | #Scheme | Scheme | (do ((i 1 (+ i 1)))
((> i 100))
(display
(cond ((= 0 (modulo i 15)) "FizzBuzz")
((= 0 (modulo i 3)) "Fizz")
((= 0 (modulo i 5)) "Buzz")
(else i)))
(newline)) |
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... | #Red | Red |
Red [Description: "Prime checker/generator/counter"]
context [
poke noprime: make bitset! 3 1 true
top: 2
noprimes: function [n [integer!] /extern top][
either top < n [
n: n + 100
r: 2
while [r * r <= n][
repeat q n / r - 1 [poke noprime q ... |
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:... | #BCPL | BCPL | get "libhdr"
manifest
$( bfeof = 0
$)
let reads(v) be
$( let ch = ?
v%0 := 0
ch := rdch()
until ch = '*N' do
$( v%0 := v%0 + 1
v%(v%0) := ch
ch := rdch()
$)
$)
let contains(str, ch) = valof
$( for i = 1 to str%0 do
if ch = str%i then resultis true
resultis false... |
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.... | #Ceylon | Ceylon | import ceylon.random {
DefaultRandom
}
shared void run() {
value mutationRate = 0.05;
value childrenPerGeneration = 100;
value target = "METHINKS IT IS LIKE A WEASEL";
value alphabet = {' ', *('A'..'Z')};
value random = DefaultRandom();
value randomLetter => random.nextElement(alphabet);
function fitn... |
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 ... | #Lasso | Lasso |
define fibonacci(n::integer) => {
#n < 1 ? return false
local(
swap = 0,
n1 = 0,
n2 = 1
)
loop(#n) => {
#swap = #n1 + #n2;
#n2 = #n1;
#n1 = #swap;
}
return #n1
}
fibonacci(0) //->output false
fibonacci(1) //->output 1
fibonacci(2) //->output 1
fibonacci(3) //->output 2
... |
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 |... | #zkl | zkl | fcn f(n){ (1).pump(n.toFloat().sqrt(), List,
'wrap(m){((n % m)==0) and T(m,n/m) or Void.Skip}) }
fcn g(n){ [[(m); [1..n.toFloat().sqrt()],'{n%m==0}; '{T(m,n/m)} ]] } // list comprehension |
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 |... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 INPUT "Enter a number or 0 to exit: ";n
20 IF n=0 THEN STOP
30 PRINT "Factors of ";n;": ";
40 FOR i=1 TO n
50 IF FN m(n,i)=0 THEN PRINT i;" ";
60 NEXT i
70 DEF FN m(a,b)=a-INT (a/b)*b |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #OCaml | OCaml | let hq9p line =
let accumulator = ref 0 in
for i = 0 to (String.length line - 1) do
match line.[i] with
| 'h' | 'H' -> print_endline "Hello, world!"
| 'q' | 'Q' -> print_endline line
| '9' -> beer 99
| '+' -> incr accumulator
done |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #PARI.2FGP | PARI/GP | beer(n)={
if(n == 1,
print("1 bottle of beer on the wall");
print("1 bottle of beer");
print("Take one down and pass it around");
print("No bottles of beer on the wall")
,
print(n" bottles of beer on the wall");
print(n" bottles of beer");
print("Take one down and pass it around");
p... |
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... | #Lua | Lua | -- utility method to escape punctuation
function normalize(str)
local result = str:gsub("(%p)", "%%%1")
-- print(result)
return result
end
-- utility method to split string into lines
function get_lines(str)
local t = {}
for line in str:gmatch("([^\n\r]*)[\n\r]*") do
table.insert(t, line)
... |
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... | #Oz | Oz | declare
proc {Foo}
for I in 1..2 do
try
{Bar I}
catch u0 then {System.showInfo "Procedure Foo caught exception u0"}
end
end
end
proc {Bar I} {Baz I} end
proc {Baz I}
if I == 1 then
raise u0 end
else
raise u1 end
end
end
in
{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... | #PARI.2FGP | PARI/GP | call = 0;
U0() = error("x = ", 1, " should not happen!");
U1() = error("x = ", 2, " should not happen!");
baz(x) = if(x==1, U0(), x==2, U1());x;
bar() = baz(call++);
foo() = if(!call, iferr(bar(), E, printf("Caught exception, call=%d",call)), bar()) |
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
| #JavaScript | JavaScript | function doStuff() {
throw new Error('Not implemented!');
} |
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
| #jq | jq | try FILTER catch CATCHER |
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
| #Forth | Forth | s" 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
| #Fortran | Fortran |
program SystemTest
integer :: i
call execute_command_line ("ls", exitstat=i)
end program SystemTest
|
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... | #AsciiDots | AsciiDots |
/---------*--~-$#-&
| /--;---\| [!]-\
| *------++--*#1/
| | /1#\ ||
[*]*{-}-*~<+*?#-.
*-------+-</
\-#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... | #Maxima | Maxima | "^^^"(a, n) := block(
[p: 1],
while n > 0 do (
if oddp(n) then p: p * a,
a: a * a,
n: quotient(n, 2)
),
p
)$
infix("^^^")$
2 ^^^ 10;
1024
2.5 ^^^ 10;
9536.7431640625 |
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... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | С/П x^y С/П |
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... | #Ruby | Ruby | # Define a class which always returns itself for everything
class HopelesslyEgocentric
def method_missing(what, *args) self end
end
def if2(cond1, cond2)
if cond1 and cond2
yield
HopelesslyEgocentric.new
elsif cond1
Class.new(HopelesslyEgocentric) do
def else1; yield; HopelesslyEgocentric.new ... |
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... | #Rust | Rust | #![allow(unused_variables)]
macro_rules! if2 {
($cond1: expr, $cond2: expr
=> $both:expr
=> $first: expr
=> $second:expr
=> $none:expr)
=> {
match ($cond1, $cond2) {
(true, true) => $both,
(true, _ ) => $first,
(_ , true) => $s... |
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)
... | #Sed | Sed | #n
# doesn't work if there's no input
# initialize counters (0 = empty) and value
s/.*/ 0/
: loop
# increment counters, set carry
s/^\(a*\) \(b*\) \([0-9][0-9]*\)/\1a \2b \3@/
# propagate carry
: carry
s/ @/ 1/
s/9@/@0/
s/8@/9/
s/7@/8/
s/6@/7/
s/5@/6/
s/4@/5/
s/3@/4/
s/2@/3/
s/1@/2/
s/0@/1/
/@/b carry
# save state
h
#... |
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... | #REXX | REXX | /*REXX program calculates and displays primes using an extendible prime number generator*/
parse arg f .; if f=='' then f= 20 /*allow specifying number for 1 ──► F.*/
_i= ' (inclusive) '; _b= 'between '; _tnp= 'the number of primes' _b; _tn= 'the primes'
call primes f; do j=1 for f; $= $ @.... |
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:... | #Brainf.2A.2A.2A | Brainf*** |
>>>,[->+>+<<]>>[-<<+>>]>++++[<++++++++>-]<+<[->>+>>+<<<<]>>>>[-<<<<+>>
>>]<<<[->>+>+<<<]>>>[-<<<+>>>]<<[>[->+<]<[-]]>[-]>[[-]<<<<->-<[->>+>>+
<<<<]>>>>[-<<<<+>>>>]<<<[->>+>+<<<]>>>[-<<<+>>>]<<[>[->+<]<[-]]>[-]>]<
<<<[->>+<<]>[->+<]>[[-]<<<[->+>+<<]>>[-<<+>>]>++++++[<+++++++>-]<+<[->
>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>... |
http://rosettacode.org/wiki/Evolutionary_algorithm | Evolutionary algorithm | Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its argument to the target string.... | #Clojure | Clojure | (def c 100) ;number of children in each generation
(def p 0.05) ;mutation probability
(def target "METHINKS IT IS LIKE A WEASEL")
(def tsize (count target))
(def alphabet " ABCDEFGHIJLKLMNOPQRSTUVWXYZ") |
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 ... | #Latitude | Latitude | fibo := {
takes '[n].
if { n <= 1. } then {
n.
} else {
fibo (n - 1) + fibo (n - 2).
}.
}. |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Pascal | Pascal | program HQ9;
procedure runCode(code: string);
var
c_len, i, bottles: Integer;
accumulator: Cardinal;
begin
c_len := Length(code);
accumulator := 0;
for i := 1 to c_len do
begin
case code[i] of
'Q','q':
writeln(code);
'H','h':
Writeln('Hello, world!');
'9':
beg... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | markov[ruleset_, text_] :=
Module[{terminating = False, output = text,
rules = StringCases[
ruleset, {StartOfLine ~~ pattern : Except["\n"] .. ~~
" " | "\t" .. ~~ "->" ~~ " " | "\t" .. ~~ dot : "" | "." ~~
replacement : Except["\n"] .. ~~ EndOfLine :> {pattern,
replacement, d... |
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... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 9 П4
КИП4 [x] П7 Вx {x} П8
ИП8 ИПE * П8 {x} x=0 08
П5 ИП9 П1 lg [x] 10^x П3
ИП1 П2
Сx П6
ИП2 ИП7 - x=0 70
ИП9 ^ lg [x] 1 + ИП5 - 10^x / [x]
ИП6 ИП8 x#0 50 lg [x] 1 + + 10^x *
ИП9 ИП6 10^... |
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... | #Pascal | Pascal | sub foo {
foreach (0..1) {
eval { bar($_) };
if ($@ =~ /U0/) { print "Function foo caught exception U0\n"; }
else { die; } # propagate the exception
}
}
sub bar {
baz(@_); # Nest those calls
}
sub baz {
my $i = shift;
die ($i ? "U1" : "U0");
}
foo(); |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to rais... | #Perl | Perl | sub foo {
foreach (0..1) {
eval { bar($_) };
if ($@ =~ /U0/) { print "Function foo caught exception U0\n"; }
else { die; } # propagate the exception
}
}
sub bar {
baz(@_); # Nest those calls
}
sub baz {
my $i = shift;
die ($i ? "U1" : "U0");
}
foo(); |
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.