task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Julia | Julia | function extendedsqrt(x)
try sqrt(x)
catch
if x isa Number
sqrt(complex(x, 0))
else
throw(DomainError())
end
end
end
@show extendedsqrt(1) # 1
@show extendedsqrt(-1) # 0.0 + 1.0im
@show extendedsqrt('x') # ERROR: DomainError |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Kotlin | Kotlin | // version 1.0.6
// In Kotlin all Exception classes derive from Throwable and, by convention, end with the word 'Exception'
class MyException (override val message: String?): Throwable(message)
fun foo() {
throw MyException("Bad foo!")
}
fun goo() {
try {
foo()
}
catch (me: MyException) {... |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Shell "dir"
Sleep |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Frink | Frink | r = callJava["java.lang.Runtime", "getRuntime"]
println[read[r.exec["dir"].getInputStream[]]] |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #FunL | FunL | import sys.execute
execute( if $os.startsWith('Windows') then 'dir' else 'ls' ) |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #ATS | ATS |
fun
fact
(
n: int
) : int = res where
{
var n: int = n
var res: int = 1
val () = while (n > 0) (res := res * n; n := n - 1)
}
|
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #Modula-2 | Modula-2 |
(* Library Interface *)
DEFINITION MODULE Exponentiation;
PROCEDURE IntExp(base, exp : INTEGER) : INTEGER;
(* Raises base to the power of exp and returns the result
both base and exp must be of type INTEGER *)
PROCEDURE RealExp(base : REAL; exp : INTEGER) : REAL;
(* Raises base to the power of exp and retur... |
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... | #Scala | Scala | scala> def if2[A](x: => Boolean)(y: => Boolean)(xyt: => A) = new {
| def else1(xt: => A) = new {
| def else2(yt: => A) = new {
| def orElse(nt: => A) = {
| if(x) {
| if(y) xyt else xt
| } else if(y) {
| yt
| } else {
| ... |
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)
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: number is 0;
begin
for number range 1 to 100 do
if number rem 15 = 0 then
writeln("FizzBuzz");
elsif number rem 5 = 0 then
writeln("Buzz");
elsif number rem 3 = 0 then
writeln("Fizz");
els... |
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... | #Ring | Ring |
see "first twenty primes : "
i = 1
nr = 0
while i <= 20
nr += 1
if isPrime(nr) see " " + nr i += 1 ok
end
see "primes between 100 and 150 : "
for nr = 100 to 150
if isPrime(nr) see " " + nr ok
next
see nl
see "primes between 7,700 and 8,000 : "
i = 0
for nr = 7700 to 8000
if isPrime(nr) i... |
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:... | #Brat | Brat |
".""X"r~"-""\/^^{vvvv}c!!!-.256.%{vvvv}c!sa\/"r~"+""\/^^{vvvv}c!!!+.
256.%{vvvv}c!sa\/"r~"[""{"r~"]""}{\/^^{vvvv}c!!!}w!"r~">""+."r~"<""
-."r~"X""\/^^{vvvv}c!!!L[+]\/+]\/+]^^3\/.+1RAp^\/+]\/[-1RA^^-]\/[-\/
"r~"\'\'1 128r@{vv0}m[0"\/.+pse!vvvv<-sh
|
http://rosettacode.org/wiki/Evolutionary_algorithm | Evolutionary algorithm | Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its argument to the target string.... | #CLU | CLU | fitness = proc (s, t: string) returns (int)
f: int := 0
for i: int in int$from_to(1,string$size(s)) do
if s[i] ~= t[i] then f := f-1 end
end
return(f)
end fitness
mutate = proc (mut: int, s: string) returns (string)
own charset: string := " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
out: array[char] ... |
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 ... | #Lean | Lean |
-- Our first implementation is the usual recursive definition:
def fib1 : ℕ → ℕ
| 0 := 0
| 1 := 1
| (n + 2) := fib1 n + fib1 (n + 1)
-- We can give a second more efficient implementation using an auxiliary function:
def fib_aux : ℕ → ℕ → ℕ → ℕ
| 0 a b := b
| (n + 1) a b := fib_aux n (a + b) a
... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use feature qw(say switch);
my @programme = <> or die "No input. Specify a program file or pipe it to the standard input.\n";
for (@programme) {
for my $char (split //) {
given ($char) {
when ('H') { hello() }
when ('Q') { qui... |
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... | #Nim | Nim | import strutils, strscans
type Rule = object
pattern: string # Input pattern.
replacement: string # Replacement string (may be empty).
terminating: bool # "true" if terminating rule.
#---------------------------------------------------------------------------------------------------
func parse(r... |
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... | #OCaml | OCaml | (* Useful for resource cleanup (such as filehandles) *)
let try_finally x f g =
try let res = f x in g x; res
with e -> g x; raise e
(* Substitute string 'b' for first occurance of regexp 'a' in 's';
* Raise Not_found if there was no occurance of 'a'. *)
let subst a b s =
ignore (Str.search_forward a s 0); (* ... |
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... | #Phix | Phix | constant U0 = 0,
U1 = 1
integer count = 0
procedure baz()
count += 1
if count=1 then
throw(U0,{{"any",{{"thing"},"you"}},"like"})
else
throw(U1)
end if
end procedure
procedure bar()
baz()
end procedure
procedure foo()
for i=1 to 2 do
try
bar()... |
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... | #PicoLisp | PicoLisp | (de foo ()
(for Tag '(U0 U1)
(catch 'U0
(bar Tag) ) ) )
(de bar (Tag)
(baz Tag) )
(de baz (Tag)
(throw Tag) )
(mapc trace '(foo bar baz))
(foo) |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #langur | langur | # do something
throw "not a math exception"
catch .e {
if .e["cat"] == "math" {
# change result...
} else {
# rethrow the exception
throw
}
} else {
# no exception
...
} |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Lasso | Lasso | protect => {
handle_error => {
// do something else
}
fail(-1,'Oops')
} |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #FutureBasic | FutureBasic |
include "ConsoleWindow"
local fn DoUnixCommand( cmd as str255 )
dim as str255 s
open "Unix", 2, cmd
while ( not eof(2) )
line input #2, s
print s
wend
close 2
end fn
fn DoUnixCommand( "ls -A" )
|
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Gambas | Gambas | Public Sub Main()
Shell "ls -aul"
End |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Genie | Genie | [indent=4]
/*
Execute system command, in Genie
valac executeSystemCommand.gs
./executeSystemCommand
*/
init
try
// Non Blocking
Process.spawn_command_line_async("ls")
except e : SpawnError
stderr.printf("%s\n", e.message) |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #AutoHotkey | AutoHotkey | MsgBox % factorial(4)
factorial(n)
{
result := 1
Loop, % n
result *= A_Index
Return result
} |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #Modula-3 | Modula-3 | MODULE Expt EXPORTS Main;
IMPORT IO, Fmt;
PROCEDURE IntExpt(arg, exp: INTEGER): INTEGER =
VAR result := 1;
BEGIN
FOR i := 1 TO exp DO
result := result * arg;
END;
RETURN result;
END IntExpt;
PROCEDURE RealExpt(arg: REAL; exp: INTEGER): REAL =
VAR result := 1.0;
BEGIN
IF exp < 0 THE... |
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... | #Scheme | Scheme |
(define-syntax if2
(syntax-rules ()
((if2 cond1 cond2 both-true first-true second-true none-true)
(let ((c2 cond2))
(if cond1
(if c2 both-true first-true)
(if c2 second-true none-true))))))
|
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
$ syntax expr: .if.().().then.().else1.().else2.().else3.().end.if is -> 25;
const proc: if (in boolean: cond1) (in boolean: cond2) then
(in proc: statements1)
else1
(in proc: statements2)
else2
(in proc: statements3)
... |
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)
... | #SenseTalk | SenseTalk | repeat 100
put "" into output
if the counter is a multiple of 3 then
put "Fizz" after output
end if
if the counter is a multiple of 5 then
put "Buzz" after output
end if
if output is empty then
put the counter into output
end if
put output
end repeat |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi... | #Ruby | Ruby | require "prime"
puts Prime.take(20).join(", ")
puts Prime.each(150).drop_while{|pr| pr < 100}.join(", ")
puts Prime.each(8000).drop_while{|pr| pr < 7700}.count
puts Prime.take(10_000).last |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:... | #Burlesque | Burlesque |
".""X"r~"-""\/^^{vvvv}c!!!-.256.%{vvvv}c!sa\/"r~"+""\/^^{vvvv}c!!!+.
256.%{vvvv}c!sa\/"r~"[""{"r~"]""}{\/^^{vvvv}c!!!}w!"r~">""+."r~"<""
-."r~"X""\/^^{vvvv}c!!!L[+]\/+]\/+]^^3\/.+1RAp^\/+]\/[-1RA^^-]\/[-\/
"r~"\'\'1 128r@{vv0}m[0"\/.+pse!vvvv<-sh
|
http://rosettacode.org/wiki/Evolutionary_algorithm | Evolutionary algorithm | Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its argument to the target string.... | #COBOL | COBOL | identification division.
program-id. evolutionary-program.
data division.
working-storage section.
01 evolving-strings.
05 target pic a(28)
value 'METHINKS IT IS LIKE A WEASEL'.
05 parent pic a(28).
05 offspring-table.
10 offspring pic a(28)
... |
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 ... | #LFE | LFE |
(defun fib
((0) 0)
((1) 1)
((n)
(+ (fib (- n 1))
(fib (- n 2)))))
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Phix | Phix | with javascript_semantics
-- copied from 99_Bottles_of_Beer
constant ninetynine = 2 -- (set this to 9 for testing)
function bottles(integer count)
if count=0 then return "no more bottles"
elsif count=1 then return "1 bottle" end if
if count=-1 then count = ninetynine end if
return sprintf("%d bott... |
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... | #Perl | Perl | @ARGV == 1 or die "Please provide exactly one source file as an argument.\n";
open my $source, '<', $ARGV[0] or die "I couldn't open \"$ARGV[0]\" for reading. ($!.)\n";
my @rules;
while (<$source>)
{/\A#/ and next;
my @a = /(.*?)\s+->\s+(\.?)(.*)/ or die "Syntax error: $_";
push @rules, \@a;}
close $source;
... |
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... | #PL.2FI | PL/I |
/* Exceptions: Catch an exception thrown in a nested call */
test: proc options (main);
/* 8/1/2011 */
declare (m, n) fixed initial (2);
declare (U0, U1) condition;
foo: procedure () returns (fixed);
on condition(U0) snap begin;
put list ('Raised con... |
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... | #Python | Python | class U0(Exception): pass
class U1(Exception): pass
def foo():
for i in range(2):
try:
bar(i)
except U0:
print("Function foo caught exception U0")
def bar(i):
baz(i) # Nest those calls
def baz(i):
raise U1 if i else U0
foo() |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to rais... | #Quackery | Quackery | [ this ] is U0
[ this ] is U1
[ 0 = iff U0 else U1
message put bail ] is baz ( n --> )
[ baz ] is bar ( n --> )
[ 2 times
[ i^
1 backup
bar
bailed if
[ message share
U0 oats iff
[ say "Exception U0 raised." cr
... |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Lingo | Lingo | -- parent script "ErrorHandler"
on alertHook (me, errorType, errorMessage, alertType)
if alertType=#alert then return 0 -- ignore programmatic alerts
-- log error in file "error.log"
fn = _movie.path&"error.log"
fp = xtra("fileIO").new()
fp.openFile(fn, 2)
if fp.status() = -37 then
fp.createFile(fn)... |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Logo | Logo | to div.checked :a :b
if :b = 0 [(throw "divzero 0)]
output :a / :b
end
to div.safely :a :b
output catch "divzero [div.checked :a :b]
end |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #gnuplot | gnuplot | !ls |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Go | Go | package main
import (
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("ls", "-l")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
} |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #AutoIt | AutoIt | ;AutoIt Version: 3.2.10.0
MsgBox (0,"Factorial",factorial(6))
Func factorial($int)
If $int < 0 Then
Return 0
EndIf
$fact = 1
For $i = 1 To $int
$fact = $fact * $i
Next
Return $fact
EndFunc |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #Nemerle | Nemerle | using System;
macro @^ (val, pow : int)
{
<[ Math.Pow($val, $pow) ]>
} |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #Nim | Nim | proc `^`[T: float|int](base: T; exp: int): T =
var (base, exp) = (base, exp)
result = 1
if exp < 0:
when T is int:
if base * base != 1: return 0
elif (exp and 1) == 0: return 1
else: return base
else:
base = 1.0 / base
exp = -exp
while exp != 0:
if (exp and 1) != 0:... |
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... | #Shen | Shen | (defmacro branch-if-macro
[branch-if Cond1 Cond2 Both Fst Snd None] ->
[if Cond1
[if Cond2 Both Fst]
[if Cond2 Snd None]]) |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #Sidef | Sidef | class if2(cond1, cond2) {
method then(block) { # both true
if (cond1 && cond2) {
block.run;
}
return self;
}
method else1(block) { # first true
if (cond1 && !cond2) {
block.run;
}
return self;
}
method else2(block) { # se... |
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)
... | #SequenceL | SequenceL | import <Utilities/Conversion.sl>;
import <Utilities/Sequence.sl>;
main(args(2)) :=
let
result[i] :=
"FizzBuzz" when i mod 3 = 0 and i mod 5 = 0
else
"Fizz" when i mod 3 = 0
else
"Buzz" when i mod 5 = 0
else
intToString(i)
foreach i within 1 ... 100;
in
delimit(result, '\n'); |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi... | #Rust | Rust | mod pagesieve;
use pagesieve::{count_primes_paged, primes_paged};
fn main() {
println!("First 20 primes:\n {:?}",
primes_paged().take(20).collect::<Vec<_>>());
println!("Primes between 100 and 150:\n {:?}",
primes_paged().skip_while(|&x| x < 100)
.take_wh... |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:... | #C | C | (ns brainfuck)
(def ^:dynamic *input*)
(def ^:dynamic *output*)
(defrecord Data [ptr cells])
(defn inc-ptr [next-cmd]
(fn [data]
(next-cmd (update-in data [:ptr] inc))))
(defn dec-ptr [next-cmd]
(fn [data]
(next-cmd (update-in data [:ptr] dec))))
(defn inc-cell [next-cmd]
(fn [data]
(next-... |
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.... | #ColdFusion | ColdFusion |
<Cfset theString = 'METHINKS IT IS LIKE A WEASEL'>
<cfparam name="parent" default="">
<Cfset theAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ">
<Cfset fitness = 0>
<Cfset children = 3>
<Cfset counter = 0>
<Cfloop from="1" to="#children#" index="child">
<Cfparam name="child#child#" default="">
<Cfparam name="fitness#c... |
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 ... | #Liberty_BASIC | Liberty BASIC |
for i = 0 to 15
print fiboR(i),fiboI(i)
next i
function fiboR(n)
if n <= 1 then
fiboR = n
else
fiboR = fiboR(n-1) + fiboR(n-2)
end if
end function
function fiboI(n)
a = 0
b = 1
for i = 1 to n
temp = a + b
a = b
b = temp
next i
fiboI = a
e... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #php | php |
/*
H Prints "Hello, world!"
Q Prints the entire text of the source code file.
9 Prints the complete canonical lyrics to "99 Bottles of Beer on the Wall"
+ Increments the accumulator.
*/
$accumulator = 0;
echo 'HQ9+: ';
$program = trim(fgets(STDIN));
foreach (str_split($program) as $chr) {
switch ($chr) {... |
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... | #Phix | Phix | procedure markov(string rules, input, expected)
sequence subs = {}, reps = {}
sequence lines = split(substitute(rules,'\t',' '),'\n')
for i=1 to length(lines) do
string li = lines[i]
if length(li) and li[1]!='#' then
integer k = match(" -> ",li)
if k then
... |
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... | #R | R |
number_of_calls_to_baz <- 0
foo <- function()
{
for(i in 1:2) tryCatch(bar())
}
bar <- function() baz()
baz <- function()
{
e <- simpleError(ifelse(number_of_calls_to_baz > 0, "U1", "U0"))
assign("number_of_calls_to_baz", number_of_calls_to_baz + 1, envir=globalenv())
stop(e)
}
|
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to rais... | #Racket | Racket |
#lang racket
(define-struct (exn:U0 exn) ())
(define-struct (exn:U1 exn) ())
(define (foo)
(for ([i 2])
(with-handlers ([exn:U0? (λ(_) (displayln "Function foo caught exception U0"))])
(bar i))))
(define (bar i)
(baz i))
(define (baz i)
(if (= i 0)
(raise (make-exn:U0 "failed 0" (current... |
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... | #Raku | Raku | sub foo() {
for 0..1 -> $i {
bar $i;
CATCH {
when /U0/ { say "Function foo caught exception U0" }
}
}
}
sub bar($i) { baz $i }
sub baz($i) { die "U$i" }
foo; |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Logtalk | Logtalk |
:- object(exceptions).
:- public(double/2).
double(X, Y) :-
catch(double_it(X,Y), Error, handler(Error, Y)).
handler(error(not_a_number(X), logtalk(This::double(X,Y), Sender)), Y) :-
% try to fix the error and resume computation;
% if not possible, rethrow the exception
... |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Lua | Lua |
error("Something bad happened!")
|
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Groovy | Groovy | println "ls -la".execute().text |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #GUISS | GUISS | Start,Programs,Accessories,MSDOS Prompt,Type:dir[enter] |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #Avail | Avail | Assert: 7! = 5040; |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #Objeck | Objeck | class Exp {
function : Main(args : String[]) ~ Nil {
Pow(2,30)->PrintLine();
Pow(2.0,30)->PrintLine();
Pow(2.0,-2)->PrintLine();
}
function : native : Pow(base : Float, exp : Int) ~ Float {
if(exp < 0) {
return 1 / base->Power(exp * -1.0);
};
ans := 1.0;
while(exp > 0) {
... |
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... | #Smalltalk | Smalltalk | or:condition2 ifBoth:bothBlk ifFirst:firstBlk ifSecond:scndBlk ifNone:noneBlk
"I know for sure, that I am true..."
^ condition2 ifTrue:bothBlk ifFalse:firstBlk |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #Standard_ML | Standard ML | (* Languages with pattern matching ALREADY HAVE THIS! *)
fun myfunc (pred1, pred2) =
case (pred1, pred2) of
(true, true) => print ("(true, true)\n")
| (true, false) => print ("(true, false)\n")
| (false, true) => print ("(false, true)\n")
| (false, false) => print ("(false, false)\n");
myfunc (true, tru... |
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)
... | #Shale | Shale | #!/usr/local/bin/shale
string library
r var
i var
i 1 =
{ i 100 <= } {
r "" =
i 3 % 0 == { r r "fizz" concat string::() = } ifthen
i 5 % 0 == { r r "buzz" concat string::() = } ifthen
r "" equals string::() { i } { r } if i "%3d: %p\n" printf
i++
} while |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: isPrime (in integer: number) is func
result
var boolean: prime is FALSE;
local
var integer: count is 2;
begin
if number = 2 then
prime := TRUE;
elsif number > 2 then
while number rem count <> 0 and count * count <= number do
incr(... |
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:... | #C.23 | C# | (ns brainfuck)
(def ^:dynamic *input*)
(def ^:dynamic *output*)
(defrecord Data [ptr cells])
(defn inc-ptr [next-cmd]
(fn [data]
(next-cmd (update-in data [:ptr] inc))))
(defn dec-ptr [next-cmd]
(fn [data]
(next-cmd (update-in data [:ptr] dec))))
(defn inc-cell [next-cmd]
(fn [data]
(next-... |
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.... | #Commodore_BASIC | Commodore BASIC | 10 N=100:P=0.05:TI$="000000"
20 Z$="METHINKS IT IS LIKE A WEASEL"
30 L=LEN(Z$)
40 DIMX(N,L)
50 FORI=1TOL
60 IFMID$(Z$,I,1)=" "THENX(0,I)=0:GOTO80
70 X(0,I)=ASC(MID$(Z$,I))-64
80 NEXT
90 FORK=1TON:FORI=1TOL:X(K,I)=INT(RND(0)*27):NEXT:NEXT
100 S=-100:B=0
110 K=B:GOSUB300
120 FORK=1TON:IFK=BTHEN150
130 FORI=1TOL:IFRND(.)<... |
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 ... | #Lingo | Lingo | on fib (n)
if n<2 then return n
return fib(n-1)+fib(n-2)
end |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #PicoLisp | PicoLisp | (de hq9+ (Code)
(let Accu 0
(for C (chop Code)
(case C
("H" (prinl "Hello, world"))
("Q" (prinl Code))
("9"
(for (N 99 (gt0 N))
(prinl N " bottles of beer on the wall")
(prinl N " bottles of beer")
... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #PowerShell | PowerShell |
function Invoke-HQ9PlusInterpreter ([switch]$Global)
{
$sb = New-Object -TypeName System.Text.StringBuilder
for ($i = 99; $i -gt 2; $i--)
{
$sb.Append((("{0,2} bottles of beer on the wall, " +
"{0,2} bottles of beer! Take one down, pass it around, " +
"... |
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... | #PHP | PHP | <?php
function markov($text, $ruleset) {
$lines = explode(PHP_EOL, $ruleset);
$rules = array();
foreach ($lines AS $line) {
$spc = "[\t ]+";
if (empty($line) OR preg_match('/^#/', $line)) {
continue;
} elseif (preg_match('/^(.+)' . $spc . '->' . $spc . '(\.?)(.*)$/', $l... |
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... | #REXX | REXX | /*REXX program creates two exceptions and demonstrates how to handle (catch) them. */
call foo /*invoke the FOO function (below). */
say 'The REXX mainline program has completed.' /*indicate that Elroy was here. */
exit ... |
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... | #Ruby | Ruby | def foo
2.times do |i|
begin
bar(i)
rescue U0
$stderr.puts "captured exception U0"
end
end
end
def bar(i)
baz(i)
end
def baz(i)
raise i == 0 ? U0 : U1
end
class U0 < StandardError; end
class U1 < StandardError; end
foo |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #M2000_Interpreter | M2000 Interpreter |
Module Errors {
Module Check {
Module Error1 {
A=1/0
}
Try ok {
Error1
}
' we get an Error, and Error$ print division by zero in module Error1
If Error or not ok then Print Error$
Error "Ne... |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Make | Make | all:
false |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Haskell | Haskell | import System.Cmd
main = system "ls"
|
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #HicEst | HicEst | SYSTEM(CoMmand='pause')
SYSTEM(CoMmand='dir & pause') |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #AWK | AWK | function fact_r(n)
{
if ( n <= 1 ) return 1;
return n*fact_r(n-1);
} |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #OCaml | OCaml | let pow one mul a n =
let rec g p x = function
| 0 -> x
| i ->
g (mul p p) (if i mod 2 = 1 then mul p x else x) (i/2)
in
g a one n
;;
pow 1 ( * ) 2 16;; (* 65536 *)
pow 1.0 ( *. ) 2.0 16;; (* 65536. *)
(* pow is not limited to exponentiation *)
pow 0 ( + ) 2 16;; (* 32 *)
pow "" ( ^ ) "abc " 10;; ... |
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... | #Tcl | Tcl | proc if2 {cond1 cond2 bothTrueBody firstTrueBody secondTrueBody bothFalseBody} {
# Must evaluate both conditions, and should do so in order
set c1 [uplevel 1 [list expr $cond1]
set c2 [uplevel 1 [list expr $cond2]
# Now use that to decide what to do
if {$c1 && $c2} {
uplevel 1 $bothTrueBody
... |
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)
... | #Shen | Shen | (define fizzbuzz
101 -> (nl)
N -> (let divisible-by? (/. A B (integer? (/ A B)))
(cases (divisible-by? N 15) (do (output "Fizzbuzz!~%")
(fizzbuzz (+ N 1)))
(divisible-by? N 3) (do (output "Fizz!~%")
(fizzbuzz (... |
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... | #Sidef | Sidef | say ("First 20: ", 20.nth_prime.primes.join(' '))
say ("Between 100 and 150: ", primes(100,150).join(' '))
say (prime_count(7700,8000), " primes between 7700 and 8000")
say ("10,000th prime: ", nth_prime(10_000)) |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:... | #C.2B.2B | C++ | (ns brainfuck)
(def ^:dynamic *input*)
(def ^:dynamic *output*)
(defrecord Data [ptr cells])
(defn inc-ptr [next-cmd]
(fn [data]
(next-cmd (update-in data [:ptr] inc))))
(defn dec-ptr [next-cmd]
(fn [data]
(next-cmd (update-in data [:ptr] dec))))
(defn inc-cell [next-cmd]
(fn [data]
(next-... |
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.... | #Common_Lisp | Common Lisp | (defun fitness (string target)
"Closeness of string to target; lower number is better"
(loop for c1 across string
for c2 across target
count (char/= c1 c2)))
(defun mutate (string chars p)
"Mutate each character of string with probablity p using characters from chars"
(dotimes (n (length strin... |
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 ... | #Lisaac | Lisaac | - fib(n : UINTEGER_32) : UINTEGER_64 <- (
+ result : UINTEGER_64;
(n < 2).if {
result := n;
} else {
result := fib(n - 1) + fib(n - 2);
};
result
); |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #PureBasic | PureBasic | Procedure hq9plus(code.s)
Protected accumulator, i, bottles
For i = 1 To Len(code)
Select Mid(code, i, 1)
Case "h", "H"
PrintN("Hello, world!")
Case "q", "Q"
PrintN(code)
Case "9"
bottles = 99
While bottles
PrintN(Str(bottles) + " bottles of beer on th... |
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... | #PicoLisp | PicoLisp | (de markov (File Text)
(use (@A @Z R)
(let Rules
(make
(in File
(while (skip "#")
(when (match '(@A " " "-" ">" " " @Z) (replace (line) "@" "#"))
(link (cons (clip @A) (clip @Z))) ) ) ) )
(setq Text (chop Text))
(pack
... |
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... | #Prolog | Prolog | :- module('markov.pl', [markov/3, apply_markov/3]).
:- use_module(library(lambda)).
apply_markov(Rules, Sentence, Replacement) :-
maplist(\X^Y^(atom_chars(X, Ch), phrase(markov(Y), Ch, [])), Rules, TmpRules),
% comments produce empty rules
exclude(=([]), TmpRules, LstRules),
atom_chars(Sentence, L... |
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... | #Rust | Rust | #[derive(Debug)]
enum U {
U0(i32),
U1(String),
}
fn baz(i: u8) -> Result<(), U> {
match i {
0 => Err(U::U0(42)),
1 => Err(U::U1("This will be returned from main".into())),
_ => Ok(()),
}
}
fn bar(i: u8) -> Result<(), U> {
baz(i)
}
fn foo() -> Result<(), U> {
for i i... |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to rais... | #Scala | Scala | object ExceptionsTest extends App {
class U0 extends Exception
class U1 extends Exception
def foo {
for (i <- 0 to 1)
try {
bar(i)
} catch { case e: U0 => println("Function foo caught exception U0") }
}
def bar(i: Int) {
def baz(i: Int) = { if (i == 0) throw new U0 else throw n... |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Maple | Maple |
errorproc:=proc(n)
local a;
try
a:=1/n;
catch "numeric exception: division by zero":
error "Something went wrong when dividing."
end try;
end proc;
|
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | f[x_] := If[x > 10, Throw[overflow], x!]
Example usage :
Catch[f[2] + f[11]]
-> overflow
Catch[f[2] + f[3]]
-> 8 |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #HolyC | HolyC | Dir; |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Icon_and_Unicon | Icon and Unicon | procedure main()
write("Trying command ",cmd := if &features == "UNIX" then "ls" else "dir")
system(cmd)
end |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #IDL | IDL | $ls |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #Axe | Axe | Lbl FACT
1→R
For(I,1,r₁)
R*I→R
End
R
Return |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #Oforth | Oforth | : powint(r, n)
| i |
1 n abs loop: i [ r * ]
n isNegative ifTrue: [ inv ] ;
2 3 powint println
2 powint(3) println
1.2 4 powint println
1.2 powint(4) println |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #PARI.2FGP | PARI/GP | ex(a, b)={
my(c = 1);
while(b > 1,
if(b % 2, c *= a);
a = a^2;
b >>= 1
);
a * c
}; |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #TXR | TXR | (defmacro if2 (cond1 cond2 both first second . neither)
(let ((res1 (gensym))
(res2 (gensym)))
^(let ((,res1 ,cond1)
(,res2 ,cond2))
(cond ((and ,res1 ,res2) ,both)
(,res1 ,first)
(,res2 ,second)
(t ,*neither)... |
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.