task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #BASIC256 | BASIC256 |
# Intérprete de HQ9+
global codigo
codigo = ""
function HQ9plus(codigo)
acumulador = 0
HQ9plus1 = ""
for cont = 1 to length(codigo)
op = upper(mid(codigo, cont, 1))
begin case
case op = "H"
HQ9plus1 = HQ9plus1 + "Hello, world!"
case op = "Q"
HQ9plus1 = HQ9plus1 + codigo
case op = "9"
... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #BBC_BASIC | BBC BASIC | PROChq9plus("hq9+HqQ+Qq")
END
DEF PROChq9plus(code$)
LOCAL accumulator%, i%, bottles%
FOR i% = 1 TO LEN(code$)
CASE MID$(code$, i%, 1) OF
WHEN "h","H": PRINT "Hello, world!"
WHEN "q","Q": PRINT code$
WHEN "9":
bottles% = 99
WH... |
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... | #AutoHotkey | AutoHotkey | MsgBox % Pow(5,3)
MsgBox % Pow(2.5,4)
Pow(x, n){
r:=1
loop %n%
r *= x
return r
} |
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... | #AWK | AWK | $ awk 'function pow(x,n){r=1;for(i=0;i<n;i++)r=r*x;return r}{print pow($1,$2)}'
|
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
my $nzero = -0.0;
my $nan = 0 + "nan";
my $pinf = +"inf";
my $ninf = -"inf";
printf "\$nzero = %.1f\n", $nzero;
print "\$nan = $nan\n";
print "\$pinf = $pinf\n";
print "\$ninf = $ninf\n\n";
printf "atan2(0, 0) = %g\n", atan2(0, 0);
printf "atan2(0, \$nzero) = %g\n", atan2... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Go | Go | #
# snusp.icn, A Modular SNUSP interpreter
#
$define VERSION 0.6
# allow a couple of cli options
link options
# directions
$define DRIGHT 1
$define DLEFT 2
$define DUP 3
$define DDOWN 4
record position(row, col)
global dir, ip, ram
procedure main(argv)
local ch, codespace, col, dp, fn, line
local r... |
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... | #Factor | Factor | ( scratchpad ) : 2ifte ( ..a ?0 ?1 quot0: ( ..a -- ..b ) quot1: ( ..a -- ..b ) quot2: ( ..a -- ..b ) quot3: ( ..a -- ..b ) -- ..b )
[ [ if ] curry curry ] 2bi@ if ; inline
( scratchpad ) 3 [ 0 > ] [ even? ] bi [ 0 ] [ 1 ] [ 2 ] [ 3 ] 2ifte .
2 |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #Fennel | Fennel | ;; Fennel, being a Lisp, provides a way to define macros for new syntax.
;; The "`" and "," characters are used to construct a template for the macro.
(macro if2 [cond1 cond2 both first second none]
`(if ,cond1
(if ,cond2 ,both ,first)
(if ,cond2 ,second ,none)))
(fn test-if2 [x y]
(if2 x y
(print "... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Lua | Lua | print("5^3^2 = " .. 5^3^2)
print("(5^3)^2 = " .. (5^3)^2)
print("5^(3^2) = " .. 5^(3^2)) |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Maple | Maple | 5^3^2;
(5^3)^2;
5^(3^2); |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | a = "5^3^2";
Print[a <> " = " <> ToString[ToExpression[a]]]
b = "(5^3)^2";
Print[b <> " = " <> ToString[ToExpression[b]]]
c = "5^(3^2)";
Print[c <> " = " <> ToString[ToExpression[c]]] |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #min | min | 5 3 2 pow pow
"5 3 2 ^ ^ " print! puts!
5 3 pow 2 pow
"5 3 ^ 2 ^ " print! puts! |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Wren | Wren | var a = [1, 4, 17, 8, -21, 6, -11, -2, 18, 31]
System.print("The original array is : %(a)")
System.print("\nFiltering to a new array :-")
var evens = a.where { |e| e%2 == 0 }.toList
System.print("The even numbers are : %(evens)")
System.print("The original array is still : %(a)")
// Destructive filt... |
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)
... | #Q | Q |
q){(sum 1 2*0=x mod/:3 5)'[`$string x;`fizz;`buzz;`fizzbuzz]}1+til 20
`1`2`fizz`4`buzz`fizz`7`8`fizz`buzz`11`fizz`13`14`fizzbuzz`16`17`fizz`19`buzz |
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... | #Fortran | Fortran | DO WHILE(F*F <= LST) !But, F*F might overflow the integer limit so instead,
DO WHILE(F <= LST/F) !Except, LST might also overflow the integer limit, so
DO WHILE(F <= (IST + 2*(SBITS - 1))/F) !Which becomes...
DO WHILE(F <= IST/F + (MOD(IST,F) + 2*(SBITS - 1))/F) ... |
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 ... | #Groovy | Groovy | def rFib
rFib = {
it == 0 ? 0
: it == 1 ? 1
: it > 1 ? rFib(it-1) + rFib(it-2)
/*it < 0*/: rFib(it+2) - rFib(it+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 |... | #PureBasic | PureBasic | Procedure PrintFactors(n)
Protected i, lim=Round(sqr(n),#PB_Round_Up)
NewList F.i()
For i=1 To lim
If n%i=0
AddElement(F()): F()=i
AddElement(F()): F()=n/i
EndIf
Next
;- Present the result
SortList(F(),#PB_Sort_Ascending)
ForEach F()
Print(str(F())+" ")
Next
EndProcedure
If Ope... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #BQN | BQN | Pl ← {(𝕩≠1)/"s"}
Lwr ← +⟜(32×1="A["⊸⍋)
nn ← {(•Fmt 𝕨)∾" "∾𝕩}´¨∾{
⟨
⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer on the wall"⟩
⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer"⟩
⟨"Take one down, pass it around"⟩
⟨𝕩-1,"bottle"∾(Pl 𝕩-1)∾" of beer on the wall"⟩
⟩
}¨⌽1+↕99
HQ9 ← {
out ← ⟨⟨"Hello, World!"⟩, ⟨𝕩⟩, nn⟩
acc ← +´... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #C | C | void runCode(const char *code)
{
int c_len = strlen(code);
int i, bottles;
unsigned accumulator=0;
for(i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
printf("%s\n", code);
break;
case 'H':
printf("Hello, world!... |
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... | #BASIC | BASIC | DECLARE FUNCTION powL& (x AS INTEGER, y AS INTEGER)
DECLARE FUNCTION powS# (x AS SINGLE, y AS INTEGER)
DIM x AS INTEGER, y AS INTEGER
DIM a AS SINGLE
RANDOMIZE TIMER
a = RND * 10
x = INT(RND * 10)
y = INT(RND * 10)
PRINT x, y, powL&(x, y)
PRINT a, y, powS#(a, y)
FUNCTION powL& (x AS INTEGER, y AS INTEGER)
DIM... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Phix | Phix | with javascript_semantics
constant inf = 1e300*1e300, -- (works on both 32 and 64 bit)
ninf = -inf,
nan = -(inf/inf),
nzero = -1/inf -- (not supported)
printf(1," inf: %f\n",{inf})
printf(1," ninf: %f\n",{ninf})
printf(1," nan: %f\n",{nan})
printf(1,"*nzero: %f\n",{nzero})
printf(1," in... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Haskell | Haskell | #
# snusp.icn, A Modular SNUSP interpreter
#
$define VERSION 0.6
# allow a couple of cli options
link options
# directions
$define DRIGHT 1
$define DLEFT 2
$define DUP 3
$define DDOWN 4
record position(row, col)
global dir, ip, ram
procedure main(argv)
local ch, codespace, col, dp, fn, line
local r... |
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... | #Forth | Forth | \ in this construct, either of the ELSE clauses may be omitted, just like IF-THEN.
: BOTH postpone IF postpone IF ; immediate
: ORELSE postpone THEN postpone ELSE postpone IF ; immediate
: NEITHER postpone THEN postpone THEN ; immediate
: fb ( n -- )
dup 5 mod 0= over 3 mod 0=
BOTH ." FizzBuzz "
ELSE... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Nanoquery | Nanoquery | % println 5^3^2
15625
% println (5^3)^2
15625
% println 5^(3^2)
1953125 |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Nim | Nim | import math, sequtils
echo "5^3^2 = ", 5^3^2
echo "(5^3)^2 = ", (5^3)^2
echo "5^(3^2) = ", 5^(3^2)
echo "foldl([5, 3, 2], a^b) = ", foldl([5, 3, 2], a^b)
echo "foldr([5, 3, 2], a^b) = ", foldr([5, 3, 2], a^b) |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #OCaml | OCaml | - : float = 1953125.
- : float = 1953125.
- : float = 15625.
|
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #PARI.2FGP | PARI/GP | f(s)=print(s" = "eval(s));
apply(f, ["5^3^2", "(5^3)^2", "5^(3^2)"]); |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc Filter(A, B, Option); \Select all even numbers from array A
int A, B, Option; \ and return them in B, unless Option = true
int I, J;
[J:= 0;
for I:= 1 to A(0) do
if (A(I)&1) = 0 then
[J:= J+1;
... |
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)
... | #QB64 | QB64 | For n = 1 To 100
If n Mod 15 = 0 Then
Print "FizzBuzz"
ElseIf n Mod 5 = 0 Then
Print "Buzz"
ElseIf n Mod 3 = 0 Then
Print "Fizz"
Else
Print n
End If
Next |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0
Enum SieveLimitType
number
between
countBetween
End Enum
Sub printPrimes(low As Integer, high As Integer, slt As SieveLimitType)
If high < low OrElse low < 1 Then Return ' too small
If slt <> number AndAlso slt <> between AndAlso slt <> countBetween Then Return
If slt <> numbe... |
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 ... | #Harbour | Harbour |
#include "harbour.ch"
Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))
|
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 |... | #Python | Python | >>> def factors(n):
return [i for i in range(1, n + 1) if not n%i] |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void RunCode(string code)
{
int accumulator = 0;
var opcodes = new Dictionary<char, Action>
{
{'H', () => Console.WriteLine("Hello, World!"))},
{'Q', () => Console.WriteL... |
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... | #0815 | 0815 | }:r: Start reader loop.
|~ Read n,
#:end: if n is 0 terminates
>= enqueue it as the initial product, reposition.
}:f: Start factorial loop.
x<:1:x- Decrement n.
{=*> Dequeue product, position n, multiply, update product.
^:f:
{+% Dequeue incidental 0, add to ge... |
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... | #Befunge | Befunge | v v \<
>&:32p&1-\>32g*\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... | #Brat | Brat | #Procedure
exp = { base, exp |
1.to(exp).reduce 1, { m, n | m = m * base }
}
#Numbers are weird
1.parent.^ = { rhs |
num = my
1.to(rhs).reduce 1 { m, n | m = m * num }
}
p exp 2 5 #Prints 32
p 2 ^ 5 #Prints 32 |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Ada | Ada | package Parameter is
X: Natural := 0;
Y: Natural;
end Parameter; |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #PicoLisp | PicoLisp | (load "@lib/math.l")
: (exp 1000.0) # Too large for IEEE floats
-> T
: (+ 1 2 NIL 3) # NaN propagates
-> NIL |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #PureBasic | PureBasic | Define.f
If OpenConsole()
inf = Infinity() ; or 1/None ;None represents a variable of value = 0
minus_inf = -Infinity() ; or -1/None
minus_zero = -1/inf
nan = NaN() ; or None/None
PrintN("positive infinity: "+StrF(inf))
PrintN("negative infinity: "+StrF(minus_inf))
PrintN("positive zero: "+StrF(None... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Icon_and_Unicon | Icon and Unicon | #
# snusp.icn, A Modular SNUSP interpreter
#
$define VERSION 0.6
# allow a couple of cli options
link options
# directions
$define DRIGHT 1
$define DLEFT 2
$define DUP 3
$define DDOWN 4
record position(row, col)
global dir, ip, ram
procedure main(argv)
local ch, codespace, col, dp, fn, line
local r... |
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... | #Fortran | Fortran | LOGICAL A,B !These are allocated the same storage
INTEGER IA,IB !As the default integer size.
EQUIVALENCE (IA,A),(IB,B) !So, this will cause no overlaps.
WRITE (6,*) "Boolean tests via integers..."
DO 199 IA = 0,1 !Two states for A.
DO 199 IB = 0,1 !Two states for B.
... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Perl | Perl | say "$_ = " . eval($_) for qw/5**3**2 (5**3)**2 5**(3**2)/; |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Phix | Phix | ?power(power(5,3),2)
?power(5,power(3,2))
|
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #PicoLisp | PicoLisp | : (** (** 5 3) 2)
-> 15625
: (** 5 (** 3 2))
-> 1953125 |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #PL.2FI | PL/I | exponentiation: procedure options(main);
put skip edit('5**3**2 = ', 5**3**2) (A,F(7));
put skip edit('(5**3)**2 = ', (5**3)**2) (A,F(7));
put skip edit('5**(3**2) = ', 5**(3**2)) (A,F(7));
end exponentiation; |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #XQuery | XQuery |
(: Sequence of numbers from 1 to 10 :)
let $array := (1 to 10)
(: Short version :)
let $short := $array[. mod 2 = 0]
(: Long version with a FLWOR expression :)
let $long := for $value in $array
where $value mod 2 = 0
return $value
(: Show the results :)
return
<result>
<short>{$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)
... | #Quackery | Quackery | [ times
[ i^ 1+
' echo
over 3 mod 0 = if
[ say "Fizz"
drop ' drop ]
over 5 mod 0 = if
[ say "Buzz"
drop ' drop ]
do
sp ]
cr ] is fizzbuzz ( n --> )
say 'First 100 turns in the game of fizzbuzz:' cr cr
... |
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... | #Frink | Frink | println["The first 20 primes are: " + first[primes[], 20]]
println["The primes between 100 and 150 are: " + primes[100,150]]
println["The number of primes between 7700 and 8000 are: " + length[primes[7700,8000]]]
println["The 10,000th prime is: " + nth[primes[], 10000-1]] // nth is zero-based |
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 ... | #Haskell | Haskell |
import Data.CReal
phi = (1 + sqrt 5) / 2
fib :: (Integral b) => b -> CReal 0
fib n = (phi^^n - (-phi)^^(-n))/sqrt 5
|
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 |... | #Quackery | Quackery | [ 1
[ 2dup < not while
2 << again ]
0
[ over 1 > while
dip [ 2 >> 2dup - ]
dup 1 >> unrot -
dup 0 < iff drop
else
[ 2swap nip
rot over + ]
again ] nip swap ] is isqrt ( n --> n n )
[ [] swap
dup isqrt 0 = dip
[ times
[ d... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #C.2B.2B | C++ | void runCode(string code)
{
int c_len = code.length();
unsigned accumulator=0;
int bottles;
for(int i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
cout << code << endl;
break;
case 'H':
cout << "Hello, world!" ... |
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... | #11l | 11l | F factorial(n)
V result = 1
L(i) 2..n
result *= i
R result
L(n) 0..5
print(n‘ ’factorial(n)) |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #C | C | #include <stdio.h>
#include <assert.h>
int ipow(int base, int exp)
{
int pow = base;
int v = 1;
if (exp < 0) {
assert (base != 0); /* divide by zero */
return (base*base != 1)? 0: (exp&1)? base : 1;
}
while(exp > 0 )
{
if (exp & 1) v *= pow;
pow *= pow;
exp >>= 1;
... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #AutoHotkey | AutoHotkey | #NoEnv
SetBatchLines, -1
; Check if we're executed directly:
If (A_LineFile = A_ScriptFullPath){
h27 := hailstone(27)
MsgBox % "Length of hailstone 27: " (m := h27.MaxIndex()) "`nStarts with "
. h27[1] ", " h27[2] ", " h27[3] ", " h27[4]
. "`nEnds with "
. h27[m-3] ", " h27[m-2] ", " h27[m-1] ", " h27[m]
L... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #BBC_BASIC | BBC BASIC | seqlen% = FNhailstone(27)
PRINT "Sequence length for 27 is "; seqlen%
maxlen% = 0
FOR number% = 2 TO 100000
seqlen% = FNhailstone(number%)
IF seqlen% > maxlen% THEN
maxlen% = seqlen%
maxnum% = number%
ENDIF
NEXT
PRINT "The number with the l... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Python | Python | >>> # Extreme values from expressions
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>> # Print
>>> for value in (inf, _inf, _zero, nan): print (value)
inf
-inf
-0.0
nan
>>> # Extreme values from other means
>>> float('nan'... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #R | R | # 0 and -0 are recognized but are both printed as simply 0.
1/c(0, -0, Inf, -Inf, NaN)
# Inf -Inf 0 0 NaN |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #J | J |
Note 'snusp'
Without $ character the program counter starts at top left (0 0) moving to the right (0 1)
> increment the pointer (to point to the next cell to the right).
< decrement the pointer (to point to the next cell to the left).
+ increment (increase by one) the cell at the... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Java | Java | const echo2 = raw"""
/==!/======ECHO==,==.==#
| |
$==>==@/==@/==<==#"""
@enum Direction left up right down
function snusp(datalength, progstring)
stack = Vector{Tuple{Int, Int, Direction}}()
data = zeros(datalength)
dp = ipx = ipy = 1
direction = right # default to go to right at... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #JavaScript | JavaScript | const echo2 = raw"""
/==!/======ECHO==,==.==#
| |
$==>==@/==@/==<==#"""
@enum Direction left up right down
function snusp(datalength, progstring)
stack = Vector{Tuple{Int, Int, Direction}}()
data = zeros(datalength)
dp = ipx = ipy = 1
direction = right # default to go to right at... |
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... | #Free_Pascal | Free Pascal | program fourWay(input, output, stdErr);
var
tuple: record
A: boolean;
B: char;
end;
begin
tuple.A := true;
tuple.B := 'Z';
case tuple of
(A: false; B: 'R'):
begin
writeLn('R is not good');
end;
(A: true; B: 'Z'):
begin
writeLn('Z is great');
end;
else
begin
writeLn('No');
end;
en... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Python | Python | >>> 5**3**2
1953125
>>> (5**3)**2
15625
>>> 5**(3**2)
1953125
>>> # The following is not normally done
>>> try: from functools import reduce # Py3K
except: pass
>>> reduce(pow, (5, 3, 2))
15625
>>> |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Quackery | Quackery | Welcome to Quackery.
Enter "leave" to leave the shell.
/O> $ "5 3 2 ** **" dup echo$ say " returns " quackery echo cr
... $ "5 3 ** 2 **" dup echo$ say " returns " quackery echo cr
...
5 3 2 ** ** returns 1953125
5 3 ** 2 ** returns 15625
Stack empty. |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #R | R | print(quote(5**3))
print(quote(5^3)) |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #XSLT | XSLT | <xsl:for-each select="nodes[@value mod 2 = 0]">
<xsl:value-of select="@value" />
</xsl:for-each> |
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)
... | #R | R | xx <- x <- 1:100
xx[x %% 3 == 0] <- "Fizz"
xx[x %% 5 == 0] <- "Buzz"
xx[x %% 15 == 0] <- "FizzBuzz"
xx |
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... | #Go | Go | package main
import (
"container/heap"
"fmt"
)
func main() {
p := newP()
fmt.Print("First twenty: ")
for i := 0; i < 20; i++ {
fmt.Print(p(), " ")
}
fmt.Print("\nBetween 100 and 150: ")
n := p()
for n <= 100 {
n = p()
}
for ; n < 150; n = p() {
fmt... |
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 ... | #Haxe | Haxe | static function fib(steps:Int, handler:Int->Void)
{
var current = 0;
var next = 1;
for (i in 1...steps)
{
handler(current);
var temp = current + next;
current = next;
next = temp;
}
handler(current);
} |
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 |... | #R | R | factors <- function(n)
{
if(length(n) > 1)
{
lapply(as.list(n), factors)
} else
{
one.to.n <- seq_len(n)
one.to.n[(n %% one.to.n) == 0]
}
} |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Ceylon | Ceylon | shared void run() {
void eval(String code) {
variable value accumulator = 0;
for(c in code.trimmed.lowercased) {
switch(c)
case('h') {
print("Hello, world!");
}
case('q') {
print(code);
}
case('9') {
function bottles(Integer i) =>
switch(i)
case(0) "No bottles"
... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Clojure | Clojure | (ns anthony.random.hq9plus
(:require [clojure.string :as str]))
(defn bottles []
(loop [bottle 99]
(if (== bottle 0)
()
(do
(println (str bottle " bottles of beer on the wall"))
(println (str bottle " bottles of beer"))
(println "Take one down, pass it around")
(pri... |
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... | #11l | 11l | T U0 {}
T U1 {}
F baz(i)
I i == 0
X U0()
E
X U1()
F bar(i)
baz(i)
F foo()
L(i) 0..1
X.try
bar(i)
X.catch U0
print(‘Function foo caught exception U0’)
foo() |
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... | #360_Assembly | 360 Assembly | FACTO CSECT
USING FACTO,R13
SAVEAREA B STM-SAVEAREA(R15)
DC 17F'0'
DC CL8'FACTO'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 base register and savearea pointer
ZAP N,=P'1' n=1
LOOPN ... |
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... | #C.23 | C# |
static void Main(string[] args)
{
Console.WriteLine("5^5 = " + Expon(5, 5));
Console.WriteLine("5.5^5 = " + Expon(5.5, 5));
Console.ReadLine();
}
static double Expon(int Val, int Pow)
{
return Math.Pow(Val, Pow);
}
static double Expon(double Val, int Pow)
{
return Math.Pow(Val, Pow);
}
|
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #C | C | #ifndef HAILSTONE
#define HAILSTONE
long hailstone(long, long**);
void free_sequence(long *);
#endif/*HAILSTONE*/ |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Clojure | Clojure | .
├── clojure.jar
└── rosetta_code
├── frequent_hailstone_lengths.clj
└── hailstone_sequence.clj
|
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | local hailstone:
swap [ over ]
while < 1 dup:
if % over 2:
#odd
++ * 3
else:
#even
/ swap 2
swap push-through rot dup
drop
if = (name) :(main):
local :h27 hailstone 27
!. = 112 len h27
!. = 27 h27! 0
!. = 82 h27! 1
!. = 41 h27! 2
!. = 124 h27! 3
!. = 8 h27! 108
!. = 4 h27! 109
!. = 2 h27... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Racket | Racket | #lang racket
(define division-by-zero (/ 1.0 0.0)) ;+inf.0
(define negative-inf (- (/ 1.0 0.0))) ;-inf.0
(define zero 0.0) ;0.0
(define negative-zero (- 0.0)) ;-0.0
(define nan (/ 0.0 0.0)) ;+nan.0
(displayln division-by-zero)
(displayln negative-inf)
(... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Raku | Raku | print qq:to 'END'
positive infinity: {1.8e308}
negative infinity: {-1.8e308}
negative zero: {0e0 * -1}
not a number: {0 * 1e309}
+Inf + 2.0 = {Inf + 2}
+Inf - 10.1 = {Inf - 10.1}
0 * +Inf = {0 * Inf}
+Inf + -Inf = {Inf + -Inf}
+Inf == -Inf = {+Inf == -Inf}
(-Inf+0i)**.5 = {(-Inf+0i)**.5}
NaN + 1.0 = {NaN + 1.0}
NaN + N... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Julia | Julia | const echo2 = raw"""
/==!/======ECHO==,==.==#
| |
$==>==@/==@/==<==#"""
@enum Direction left up right down
function snusp(datalength, progstring)
stack = Vector{Tuple{Int, Int, Direction}}()
data = zeros(datalength)
dp = ipx = ipy = 1
direction = right # default to go to right at... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Kotlin | Kotlin | // version 1.1.2
// requires 5 chars (10 bytes) of data store
const val hw = """
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/"""
// input is a multi-line string.
fun snusp(dlen: Int, raw: String) {... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Macro If2(condition1, condition2)
#Define Else1 ElseIf CBool(condition1) Then
#Define Else2 ElseIf CBool(condition2) Then
If CBool(condition1) AndAlso CBool(condition2) Then
#Endmacro
Sub test(a As Integer, b As Integer)
If2(a > 0, b > 0)
print "both positive"
Else1
print "first posit... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Racket | Racket | #lang racket
;; 5**3**2 depends on associativity of ** : Racket's (scheme's) prefix function
;; calling syntax only allows for pairs of arguments for expt.
;; So no can do for 5**3**2
;; (5**3)**2
(displayln "prefix")
(expt (expt 5 3) 2)
;; (5**3)**2
(expt 5 (expt 3 2))
;; There is also a less-used infix operation ... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Raku | Raku | use MONKEY-SEE-NO-EVAL;
sub demo($x) { say " $x\t───► ", EVAL $x }
demo '5**3**2'; # show ** is right associative
demo '(5**3)**2';
demo '5**(3**2)';
demo '[**] 5,3,2'; # reduction form, show only final result
demo '[\**] 5,3,2'; # triangle reduction, show growing results
# Unicode postfix exponents are ... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Red | Red | Red["Exponentiation order"]
exprs: [
[5 ** 3 ** 2]
[(5 ** 3) ** 2]
[5 ** (3 ** 2)]
[power power 5 3 2] ;-- functions too
[power 5 power 3 2]
]
foreach expr exprs [
print [mold/only expr "=" do expr]
if find expr '** [
print [mold/only expr "=" math expr "using math"]
]
] |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Z80_Assembly | Z80 Assembly | TestArray_Metadata:
byte 4,4 ;4 rows, 4 columns.
TestArray:
byte 0,1,2,3
byte 4,5,6,7
byte 8,9,10,11
byte 12,13,14,15
OutputArray_Metadata:
byte 2,4
OutputArray:
ds 8,0 ;16 bytes each equaling zero
FilterEvenValues:
ld hl,TestArray_Metadata
ld a,(hl)
inc hl
ld b,(hl)
inc hl ;LD HL,TestA... |
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)
... | #Racket | Racket | #lang racket
(for ([n (in-range 1 101)])
(displayln
(match (gcd n 15)
[15 "fizzbuzz"]
[3 "fizz"]
[5 "buzz"]
[_ 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... | #Haskell | Haskell | #!/usr/bin/env runghc
import Data.List
import Data.Numbers.Primes
import System.IO
firstNPrimes :: Integer -> [Integer]
firstNPrimes n = genericTake n primes
primesBetweenInclusive :: Integer -> Integer -> [Integer]
primesBetweenInclusive lo hi =
dropWhile (< lo) $ takeWhile (<= hi) primes
nthPrime :: Integer... |
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 ... | #HicEst | HicEst | REAL :: Fibonacci(10)
Fibonacci = ($==2) + Fibonacci($-1) + Fibonacci($-2)
WRITE(ClipBoard) Fibonacci ! 0 1 1 2 3 5 8 13 21 34 |
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 |... | #Racket | Racket |
#lang racket
;; a naive version
(define (naive-factors n)
(for/list ([i (in-range 1 (add1 n))] #:when (zero? (modulo n i))) i))
(naive-factors 120) ; -> '(1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120)
;; much better: use `factorize' to get prime factors and construct the
;; list of results from that
(require math)... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #CLU | CLU | % This program uses the "get_argv" function from PCLU's "useful.lib"
hq9plus = cluster is load, run
rep = string
own po: stream := stream$primary_output()
bottles = proc (n: int) returns (string)
if n=0 then return("No more bottles ")
elseif n=1 then return("1 bottle ")
else retu... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Exec-Hq9.
DATA DIVISION.
LOCAL-STORAGE SECTION.
78 Code-Length VALUE 256.
01 i PIC 999.
01 accumulator PIC 999.
01 bottles PIC 999.
LINKAGE SECTION.
01 hq9-code PIC X(Code-Length).
... |
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... | #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
procedure Exceptions_From_Nested_Calls is
U0 : exception;
U1 : exception;
Baz_Count : Natural := 0;
procedure Baz is
begin
Baz_Count := Baz_Count + 1;
if Baz_Count = 1 then
raise U0;
else
raise U1;
end if;
end Baz;
proce... |
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... | #Aime | Aime | void
baz(integer i)
{
error(cat("U", itoa(i)));
}
void
bar(integer i)
{
baz(i);
}
void
foo(void)
{
integer i;
i = 0;
while (i < 2) {
text e;
if (trap_d(e, bar, i)) {
o_form("Exception `~' thrown\n", e);
if (e != "U0") {
o_text("will not catch excepti... |
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
| #11l | 11l | os:(‘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... | #68000_Assembly | 68000 Assembly | Factorial:
;input: D0.W: number you wish to get the factorial of.
;output: D0.L
CMP.W #0,D0
BEQ .isZero
CMP.W #1,D0
BEQ .isOne
MOVEM.L D4-D5,-(SP)
MOVE.W D0,D4
MOVE.W D0,D5
SUBQ.W #2,D5 ;D2 = LOOP COUNTER.
;Since DBRA stops at FFFF we can't use it as our multiplier.
;If we did, we'd always return 0!
.lo... |
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... | #C.2B.2B | C++ | template<typename Number>
Number power(Number base, int exponent)
{
int zerodir;
Number factor;
if (exponent < 0)
{
zerodir = 1;
factor = Number(1)/base;
}
else
{
zerodir = -1;
factor = base;
}
Number result(1);
while (exponent != 0)
{
if (exponent % 2 != 0)
{
resu... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Factor | Factor | ! rosetta/hailstone/hailstone.factor
USING: arrays io kernel math math.ranges prettyprint sequences vectors ;
IN: rosetta.hailstone
: hailstone ( n -- seq )
[ 1vector ] keep
[ dup 1 number= ]
[
dup even? [ 2 / ] [ 3 * 1 + ] if
2dup swap push
] until
drop ;
<PRIVATE
: main ( -- )
... |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming langua... | #Go | Go | // modulino.go
package main
import "fmt"
// Function borrowed from Hailstone sequence task.
// 1st arg is the number to generate the sequence for.
// 2nd arg is a slice to recycle, to reduce garbage.
func hailstone(n int, recycle []int) []int {
s := append(recycle[:0], n)
for n > 1 {
if n&1 == 0 {
... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #REXX | REXX | /*REXX pgm shows smallest & largest positive numbers that can be expressed, compares 0's*/
parse version v; say 'version=' v; say
zero= '0.0' /*a (positive) value for zero. */
negZero= '-0.0' /*" negative " " " */
sa... |
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.