code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
null | 868Extend your language
| 11kotlin
| 1iqpd |
class Integer
def factors() (1..self).select { |n| (self % n).zero? } end
end
p 45.factors | 861Factors of an integer
| 14ruby
| 06msu |
package Hailstone;
sub seq {
my $x = shift;
$x == 1 ? (1) : ($x & 1)? ($x, seq($x * 3 + 1))
: ($x, seq($x / 2))
}
my %cache = (1 => 1);
sub len {
my $x = shift;
$cache{$x} //= 1 + (
$x & 1 ? len($x * 3 + 1)
: len($x / 2))
}
unless (caller) {
for (1 .. 100_000) {
my $l = len($_);
($m, $len) = ($_, $l) if $l > $len;
}
print "seq of 27 - $cache{27} elements: @{[seq(27)]}\n";
print "Longest sequence is for $m: $len\n";
}
1; | 875Executable library
| 2perl
| szwq3 |
let negInf = -1.0 / 0.0
let inf = 1.0 / 0.0 | 865Extreme floating point values
| 17swift
| om68k |
$ include ;
const proc: snusp (in string: sourceCode, in integer: memSize, inout file: input, inout file: output) is func
local
var array string: instructions is 0 times ;
var array char: memory is 0 times ' ';
var integer: dataPointer is 1;
var integer: instrPtrRow is 0;
var integer: instrPtrColumn is 0;
var integer: rowDir is 0;
var integer: columnDir is 1;
var integer: helpDir is 0;
var integer: row is 0;
begin
instructions:= split(sourceCode, );
memory:= memSize times '\0;';
for key row range instructions do
if pos(instructions[row], '$') <> 0 then
instrPtrRow:= row;
instrPtrColumn:= pos(instructions[row], '$');
end if;
end for;
while instrPtrRow >= 1 and instrPtrRow <= length(instructions) and
instrPtrColumn >= 1 and instrPtrColumn <= length(instructions[instrPtrRow]) do
case instructions[instrPtrRow][instrPtrColumn] of
when {'>'}: incr(dataPointer);
when {'<'}: decr(dataPointer);
when {'+'}: incr(memory[dataPointer]);
when {'-'}: decr(memory[dataPointer]);
when {'.'}: write(output, memory[dataPointer]);
when {','}: memory[dataPointer]:= getc(input);
when {'/'}: helpDir:= rowDir;
rowDir:= -columnDir;
columnDir:= -helpDir;
when {'\\'}: helpDir:= rowDir;
rowDir:= columnDir;
columnDir:= helpDir;
when {'!'}: instrPtrRow +:= rowDir;
instrPtrColumn +:= columnDir;
when {'?'}: if memory[dataPointer] = '\0;' then
instrPtrRow +:= rowDir;
instrPtrColumn +:= columnDir;
end if;
end case;
instrPtrRow +:= rowDir;
instrPtrColumn +:= columnDir;
end while;
end func;
const string: helloWorld is ;
const proc: main is func
begin
snusp(helloWorld, 5, IN, OUT);
end func; | 872Execute SNUSP
| 14ruby
| 97cmz |
null | 868Extend your language
| 1lua
| ans1v |
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun generatePrimes() = sequence {
yield(2)
var p = 3
while (p <= Int.MAX_VALUE) {
if (isPrime(p)) yield(p)
p += 2
}
}
fun main(args: Array<String>) {
val primes = generatePrimes().take(10000) | 869Extensible prime generator
| 11kotlin
| edsa4 |
fn main() {
assert_eq!(vec![1, 2, 4, 5, 10, 10, 20, 25, 50, 100], factor(100)); | 861Factors of an integer
| 15rust
| 8y907 |
typedef struct { char * s; size_t alloc_len; } string;
typedef struct {
char *pat, *repl;
int terminate;
} rule_t;
typedef struct {
int n;
rule_t *rules;
char *buf;
} ruleset_t;
void ruleset_del(ruleset_t *r)
{
if (r->rules) free(r->rules);
if (r->buf) free(r->buf);
free(r);
}
string * str_new(const char *s)
{
int l = strlen(s);
string *str = malloc(sizeof(string));
str->s = malloc(l + 1);
strcpy(str->s, s);
str->alloc_len = l + 1;
return str;
}
void str_append(string *str, const char *s, int len)
{
int l = strlen(str->s);
if (len == -1) len = strlen(s);
if (str->alloc_len < l + len + 1) {
str->alloc_len = l + len + 1;
str->s = realloc(str->s, str->alloc_len);
}
memcpy(str->s + l, s, len);
str->s[l + len] = '\0';
}
void str_transfer(string *dest, string *src)
{
size_t tlen = dest->alloc_len;
dest->alloc_len = src->alloc_len;
src->alloc_len = tlen;
char *ts = dest->s;
dest->s = src->s;
src->s = ts;
src->s[0] = '\0';
}
void str_del(string *s)
{
if (s->s) free(s->s);
free(s);
}
void str_markov(string *str, ruleset_t *r)
{
int i, j, sl, pl;
int changed = 0, done = 0;
string *tmp = str_new();
while (!done) {
changed = 0;
for (i = 0; !done && !changed && i < r->n; i++) {
pl = strlen(r->rules[i].pat);
sl = strlen(str->s);
for (j = 0; j < sl; j++) {
if (strncmp(str->s + j, r->rules[i].pat, pl))
continue;
str_append(tmp, str->s, j);
str_append(tmp, r->rules[i].repl, -1);
str_append(tmp, str->s + j + pl, -1);
str_transfer(str, tmp);
changed = 1;
if (r->rules[i].terminate)
done = 1;
break;
}
}
if (!changed) break;
}
str_del(tmp);
return;
}
ruleset_t* read_rules(const char *name)
{
struct stat s;
char *buf;
size_t i, j, k, tmp;
rule_t *rules = 0;
int n = 0;
int fd = open(name, O_RDONLY);
if (fd == -1) return 0;
fstat(fd, &s);
buf = malloc(s.st_size + 2);
read(fd, buf, s.st_size);
buf[s.st_size] = '\n';
buf[s.st_size + 1] = '\0';
close(fd);
for (i = j = 0; buf[i] != '\0'; i++) {
if (buf[i] != '\n') continue;
if (buf[j] == '
j = i + 1;
continue;
}
for (k = j + 1; k < i - 3; k++)
if (isspace(buf[k]) && !strncmp(buf + k + 1, , 2))
break;
if (k >= i - 3) {
printf(, i - j, buf + j);
break;
}
for (tmp = k; tmp > j && isspace(buf[--tmp]); );
if (tmp < j) {
printf(, i - j, buf + j);
break;
}
buf[++tmp] = '\0';
for (k += 3; k < i && isspace(buf[++k]););
buf[i] = '\0';
rules = realloc(rules, sizeof(rule_t) * (1 + n));
rules[n].pat = buf + j;
if (buf[k] == '.') {
rules[n].terminate = 1;
rules[n].repl = buf + k + 1;
} else {
rules[n].terminate = 0;
rules[n].repl = buf + k;
}
n++;
j = i + 1;
}
ruleset_t *r = malloc(sizeof(ruleset_t));
r->buf = buf;
r->rules = rules;
r->n = n;
return r;
}
int test_rules(const char *s, const char *file)
{
ruleset_t * r = read_rules(file);
if (!r) return 0;
printf(, file);
string *ss = str_new(s);
printf(, ss->s);
str_markov(ss, r);
printf(, ss->s);
str_del(ss);
ruleset_del(r);
return printf();
}
int main()
{
test_rules(, );
test_rules(, );
test_rules(, );
test_rules(, );
test_rules(, );
return 0;
} | 877Execute a Markov algorithm
| 5c
| y4f6f |
local primegen = {
count_limit = 2,
value_limit = 3,
primelist = { 2, 3 },
nextgenvalue = 5,
nextgendelta = 2,
tbd = function(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
local limit = math.sqrt(n)
for f = 5, limit, 6 do
if n % f == 0 or n % (f+2) == 0 then return false end
end
return true
end,
needmore = function(self)
return (self.count_limit ~= nil and #self.primelist < self.count_limit)
or (self.value_limit ~= nil and self.nextgenvalue < self.value_limit)
end,
generate = function(self, count_limit, value_limit)
self.count_limit = count_limit
self.value_limit = value_limit
while self:needmore() do
if (self.tbd(self.nextgenvalue)) then
self.primelist[#self.primelist+1] = self.nextgenvalue
end
self.nextgenvalue = self.nextgenvalue + self.nextgendelta
self.nextgendelta = 6 - self.nextgendelta
end
end,
filter = function(self, f)
local list = {}
for k,v in ipairs(self.primelist) do
if (f(v)) then list[#list+1] = v end
end
return list
end,
}
primegen:generate(20, nil)
print("First 20 primes: " .. table.concat(primegen.primelist, ", "))
primegen:generate(nil, 150)
print("Primes between 100 and 150: " .. table.concat(primegen:filter(function(v) return v>=100 and v<=150 end), ", "))
primegen:generate(nil, 8000)
print("Number of primes between 7700 and 8000: " .. #primegen:filter(function(v) return v>=7700 and v<=8000 end))
primegen:generate(10000, nil)
print("The 10,000th prime: " .. primegen.primelist[#primegen.primelist])
primegen:generate(100000, nil)
print("The 100,000th prime: " .. primegen.primelist[#primegen.primelist]) | 869Extensible prime generator
| 1lua
| wf0ea |
public static long itFibN(int n)
{
if (n < 2)
return n;
long ans = 0;
long n1 = 0;
long n2 = 1;
for(n--; n > 0; n--)
{
ans = n1 + n2;
n1 = n2;
n2 = ans;
}
return ans;
} | 862Fibonacci sequence
| 9java
| xtzwy |
enum { MY_EXCEPTION = 1 };
jmp_buf env;
void foo()
{
longjmp(env, MY_EXCEPTION);
}
void call_foo()
{
switch (setjmp(env)) {
case 0:
foo();
break;
case MY_EXCEPTION:
break;
default:
}
} | 878Exceptions
| 5c
| vky2o |
def hailstone(n):
seq = [n]
while n>1:
n = 3*n + 1 if n & 1 else n
seq.append(n)
return seq
if __name__ == '__main__':
h = hailstone(27)
assert len(h)==112 and h[:4]==[27, 82, 41, 124] and h[-4:]==[8, 4, 2, 1]
print(%
max((len(hailstone(i)), i) for i in range(1,100000))) | 875Executable library
| 3python
| 03xsq |
function fib(n) {
return n<2?n:fib(n-1)+fib(n-2);
} | 862Fibonacci sequence
| 10javascript
| om986 |
def factors(num: Int) = {
(1 to num).filter { divisor =>
num % divisor == 0
}
} | 861Factors of an integer
| 16scala
| nc2ic |
module hq9plus
function main = |args| {
var accumulator = 0
let source = readln("please enter your source code: ")
foreach ch in source: chars() {
case {
when ch == 'h' or ch == 'H' {
println("Hello, world!")
}
when ch == 'q' or ch == 'Q' {
println(source)
}
when ch == '9' {
ninety9Bottles()
}
when ch == '+' {
accumulator = accumulator + 1
}
otherwise {
println("syntax error")
}
}
}
}
function bottles = |amount| -> match {
when amount == 1 then "One bottle"
when amount == 0 then "No bottles"
otherwise amount + " bottles"
}
function ninety9Bottles = {
foreach n in [99..0]: decrementBy(1) {
println(bottles(n) + " of beer on the wall,")
println(bottles(n) + " of beer!")
println("Take one down, pass it around,")
println(bottles(n - 1) + " of beer on the wall!")
}
} | 873Execute HQ9+
| 0go
| upuvt |
module Hailstone
module_function
def hailstone n
seq = [n]
until n == 1
n = (n.even?)? (n / 2): (3 * n + 1)
seq << n
end
seq
end
end
if __FILE__ == $0
include Hailstone
hs27 = hailstone 27
p [hs27.length, hs27[0..3], hs27[-4..-1]]
n, len = (1 ... 100_000) .collect {|n|
[n, hailstone(n).length]} .max_by {|n, len| len}
puts
puts
end | 875Executable library
| 14ruby
| oys8v |
// live demo: http://try.haxe.org/#2E7D4
static function hq9plus(code:String):String {
var out:String = "";
var acc:Int = 0;
for (position in 0 ... code.length) switch (code.charAt(position)) {
case "H", "h": out += "Hello, World!\n";
case "Q", "q": out += '$code\n';
case "9":
var quantity:Int = 99;
while (quantity > 1) {
out += '$quantity bottles of beer on the wall, $quantity bottles of beer.\n';
out += 'Take one down and pass it around, ${
}
out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
"Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
"No more bottles of beer on the wall, no more bottles of beer.\n" +
"Go to the store and buy some more, 99 bottles of beer on the wall.\n";
case "+": acc++;
}
return out;
} | 873Execute HQ9+
| 8haskell
| wfwed |
(try
(if (> (rand) 0.5)
(throw (RuntimeException. "oops!"))
(println "see this half the time")
(catch RuntimeException e
(println e)
(finally
(println "always see this")) | 878Exceptions
| 6clojure
| re2g2 |
object HailstoneSequence extends App { | 875Executable library
| 16scala
| flid4 |
package main
import (
"errors"
"fmt"
)
func expI(b, p int) (int, error) {
if p < 0 {
return 0, errors.New("negative power not allowed")
}
r := 1
for i := 1; i <= p; i++ {
r *= b
}
return r, nil
}
func expF(b float32, p int) float32 {
var neg bool
if p < 0 {
neg = true
p = -p
}
r := float32(1)
for pow := b; p > 0; pow *= pow {
if p&1 == 1 {
r *= pow
}
p >>= 1
}
if neg {
r = 1 / r
}
return r
}
func main() {
ti := func(b, p int) {
fmt.Printf("%d^%d: ", b, p)
e, err := expI(b, p)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(e)
}
}
fmt.Println("expI tests")
ti(2, 10)
ti(2, -10)
ti(-2, 10)
ti(-2, 11)
ti(11, 0)
fmt.Println("overflow undetected")
ti(10, 10)
tf := func(b float32, p int) {
fmt.Printf("%g^%d:%g\n", b, p, expF(b, p))
}
fmt.Println("\nexpF tests:")
tf(2, 10)
tf(2, -10)
tf(-2, 10)
tf(-2, 11)
tf(11, 0)
fmt.Println("disallowed in expI, allowed here")
tf(0, -1)
fmt.Println("other interesting cases for 32 bit float type")
tf(10, 39)
tf(10, -39)
tf(-10, 39)
} | 874Exponentiation operator
| 0go
| 7wgr2 |
int main()
{
system();
return 0;
} | 879Execute a system command
| 5c
| ubyv4 |
(^) :: (Num a, Integral b) => a -> b -> a
_ ^ 0 = 1
x ^ n | n > 0 = f x (n-1) x where
f _ 0 y = y
f a d y = g a d where
g b i | even i = g (b*b) (i `quot` 2)
| otherwise = f b (i-1) (b*y)
_ ^ _ = error "Prelude.^: negative exponent" | 874Exponentiation operator
| 8haskell
| 86s0z |
package main
import (
"fmt"
"regexp"
"strings"
)
type testCase struct {
ruleSet, sample, output string
}
func main() {
fmt.Println("validating", len(testSet), "test cases")
var failures bool
for i, tc := range testSet {
if r, ok := interpret(tc.ruleSet, tc.sample); !ok {
fmt.Println("test", i+1, "invalid ruleset")
failures = true
} else if r != tc.output {
fmt.Printf("test%d: got%q, want%q\n", i+1, r, tc.output)
failures = true
}
}
if !failures {
fmt.Println("no failures")
}
}
func interpret(ruleset, input string) (string, bool) {
if rules, ok := parse(ruleset); ok {
return run(rules, input), true
}
return "", false
}
type rule struct {
pat string
rep string
term bool
}
var (
rxSet = regexp.MustCompile(ruleSet)
rxEle = regexp.MustCompile(ruleEle)
ruleSet = `(?m:^(?:` + ruleEle + `)*$)`
ruleEle = `(?:` + comment + `|` + ruleRe + `)\n+`
comment = `#.*`
ruleRe = `(.*)` + ws + `->` + ws + `([.])?(.*)`
ws = `[\t ]+`
)
func parse(rs string) ([]rule, bool) {
if !rxSet.MatchString(rs) {
return nil, false
}
x := rxEle.FindAllStringSubmatchIndex(rs, -1)
var rules []rule
for _, x := range x {
if x[2] > 0 {
rules = append(rules,
rule{pat: rs[x[2]:x[3]], term: x[4] > 0, rep: rs[x[6]:x[7]]})
}
}
return rules, true
}
func run(rules []rule, s string) string {
step1:
for _, r := range rules {
if f := strings.Index(s, r.pat); f >= 0 {
s = s[:f] + r.rep + s[f+len(r.pat):]
if r.term {
return s
}
goto step1
}
}
return s
} | 877Execute a Markov algorithm
| 0go
| 1ojp5 |
null | 876Exceptions/Catch an exception thrown in a nested call
| 0go
| ljycw |
(.. Runtime getRuntime (exec "cmd /C dir")) | 879Execute a system command
| 6clojure
| 7w2r0 |
1.upto(100) do |n|
print if a = (n % 3).zero?
print if b = (n % 5).zero?
print n unless (a || b)
puts
end | 835FizzBuzz
| 14ruby
| adx1s |
func factors(n: Int) -> [Int] {
return filter(1...n) { n% $0 == 0 }
} | 861Factors of an integer
| 17swift
| s3yqt |
function hq9plus(code) {
var out = '';
var acc = 0;
for (var i=0; i<code.length; i++) {
switch (code.charAt(i)) {
case 'H': out += "hello, world\n"; break;
case 'Q': out += code + "\n"; break;
case '9':
for (var j=99; j>1; j--) {
out += j + " bottles of beer on the wall, " + j + " bottles of beer.\n";
out += "Take one down and pass it around, " + (j-1) + " bottles of beer.\n\n";
}
out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
"Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
"No more bottles of beer on the wall, no more bottles of beer.\n" +
"Go to the store and buy some more, 99 bottles of beer on the wall.\n";
break;
case '+': acc++; break;
}
}
return out;
} | 873Execute HQ9+
| 9java
| k0khm |
def markovInterpreterFor = { rules ->
def ruleMap = [:]
rules.eachLine { line ->
(line =~ /\s*(.+)\s->\s([.]?)(.+)\s*/).each { text, key, terminating, value ->
if (key.startsWith('#')) { return }
ruleMap[key] = [text: value, terminating: terminating]
}
}
[interpret: { text ->
def originalText = ''
while (originalText != text) {
originalText = text
for (Map.Entry e: ruleMap.entrySet()) {
if (text.indexOf(e.key) >= 0) {
text = text.replace(e.key, e.value.text)
if (e.value.terminating) {
return text
}
break
}
}
}
text
}]
} | 877Execute a Markov algorithm
| 7groovy
| jx57o |
import Control.Monad.Error
import Control.Monad.Trans (lift)
data MyError = U0 | U1 | Other deriving (Eq, Read, Show)
instance Error MyError where
noMsg = Other
strMsg _ = Other
foo = do lift (putStrLn "foo")
mapM_ (\toThrow -> bar toThrow
`catchError` \caught ->
case caught of U0 -> lift (putStrLn "foo caught U0")
_ -> throwError caught)
[U0, U1]
bar toThrow = do lift (putStrLn " bar")
baz toThrow
baz toThrow = do lift (putStrLn " baz")
throwError toThrow
main = do result <- runErrorT foo
case result of
Left e -> putStrLn ("Caught error at top level: " ++ show e)
Right v -> putStrLn ("Return value: " ++ show v) | 876Exceptions/Catch an exception thrown in a nested call
| 8haskell
| 1ohps |
public class Exp{
public static void main(String[] args){
System.out.println(pow(2,30));
System.out.println(pow(2.0,30)); | 874Exponentiation operator
| 9java
| en1a5 |
use warnings;
use strict;
use v5.10;
=for starters
Syntax:
if2 condition1, condition2, then2 {
}
else1 {
}
else2 {
}
orelse {
};
Any (but not all) of the `then' and `else' clauses can be omitted, and else1
and else2 can be specified in either order.
This extension is imperfect in several ways:
* A normal if-statement uses round brackets, but this syntax forbids them.
* Perl doesn't have a `then' keyword; if it did, it probably wouldn't be
preceded by a comma.
* Unless it's the last thing in a block, the whole structure must be followed
by a semicolon.
* Error messages appear at runtime, not compile time, and they don't show the
line where the user's syntax error occurred.
We could solve most of these problems with a source filter, but those are
dangerous. Can anyone else do better? Feel free to improve or replace.
=cut
use constant {
IdxThen => 0,
IdxElse1 => 1,
IdxElse2 => 2,
IdxOrElse => 3
};
sub orelse(&) {
my $clause = shift;
return undef, undef, undef, $clause;
}
sub else2(&@) {
my $clause = shift;
die "Can't have two `else2' clauses"
if defined $_[IdxElse2];
return (undef, $_[IdxElse1], $clause, $_[IdxOrElse]);
}
sub else1(&@) {
my $clause = shift;
die "Can't have two `else1' clauses"
if defined $_[IdxElse1];
return (undef, $clause, $_[IdxElse2], $_[IdxOrElse]);
}
sub then2(&@) {
die "Can't have two `then2' clauses"
if defined $_[1+IdxThen];
splice @_, 1+IdxThen, 1;
return @_;
}
use constant {
True => (0 == 0),
False => (0 == 1)
};
sub if2($$@) {
my $cond1 = !!shift;
my $cond2 = !!shift;
die "if2 must be followed by then2, else1, else2, &/or orelse"
if @_ != 4
or grep {defined and ref $_ ne 'CODE'} @_;
my $index;
if (!$cond1 && !$cond2) {$index = IdxOrElse}
if (!$cond1 && $cond2) {$index = IdxElse2 }
if ( $cond1 && !$cond2) {$index = IdxElse1 }
if ( $cond1 && $cond2) {$index = IdxThen }
my $closure = $_[$index];
&$closure if defined $closure;
}
sub test_bits($) {
(my $n) = @_;
print "Testing $n: ";
if2 $n & 1, $n & 2, then2 {
say "Both bits 0 and 1 are set";
}
else1 {
say "Only bit 0 is set";
}
else2 {
say "Only bit 1 is set";
}
orelse {
say "Neither bit is set";
}
}
test_bits $_ for 0 .. 7; | 868Extend your language
| 2perl
| mrvyz |
use Math::Prime::Util qw(nth_prime prime_count primes);
say "First 20: ", join(" ", @{primes(nth_prime(20))});
say "Between 100 and 150: ", join(" ", @{primes(100,150)});
say prime_count(7700,8000), " primes between 7700 and 8000";
say "${_}th prime: ", nth_prime($_) for map { 10**$_ } 1..8; | 869Extensible prime generator
| 2perl
| cju9a |
function hq9plus(code) {
var out = '';
var acc = 0;
for (var i=0; i<code.length; i++) {
switch (code.charAt(i)) {
case 'H': out += "hello, world\n"; break;
case 'Q': out += code + "\n"; break;
case '9':
for (var j=99; j>1; j--) {
out += j + " bottles of beer on the wall, " + j + " bottles of beer.\n";
out += "Take one down and pass it around, " + (j-1) + " bottles of beer.\n\n";
}
out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
"Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
"No more bottles of beer on the wall, no more bottles of beer.\n" +
"Go to the store and buy some more, 99 bottles of beer on the wall.\n";
break;
case '+': acc++; break;
}
}
return out;
} | 873Execute HQ9+
| 10javascript
| edeao |
import Data.List (isPrefixOf)
import Data.Maybe (catMaybes)
import Control.Monad
import Text.ParserCombinators.Parsec
import System.IO
import System.Environment (getArgs)
main = do
args <- getArgs
unless (length args == 1) $
fail "Please provide exactly one source file as an argument."
let sourcePath = head args
source <- readFile sourcePath
input <- getContents
case parse markovParser sourcePath source of
Right rules -> putStr $ runMarkov rules input
Left err -> hPutStrLn stderr $ "Parse error at " ++ show err
data Rule = Rule
{from :: String, terminating :: Bool, to :: String}
markovParser :: Parser [Rule]
markovParser = liftM catMaybes $
(comment <|> rule) `sepEndBy` many1 newline
where comment = char '#' >> skipMany nonnl >> return Nothing
rule = liftM Just $ liftM3 Rule
(manyTill (nonnl <?> "pattern character") $ try arrow)
(succeeds $ char '.')
(many nonnl)
arrow = ws >> string "->" >> ws <?> "whitespace-delimited arrow"
nonnl = noneOf "\n"
ws = many1 $ oneOf " \t"
succeeds p = option False $ p >> return True
runMarkov :: [Rule] -> String -> String
runMarkov rules s = f rules s
where f [] s = s
f (Rule from terminating to: rs) s = g "" s
where g _ "" = f rs s
g before ahead@(a: as) = if from `isPrefixOf` ahead
then let new = reverse before ++ to ++ drop (length from) ahead
in if terminating then new else f rules new
else g (a: before) as | 877Execute a Markov algorithm
| 8haskell
| t2of7 |
function pow(base, exp) {
if (exp != Math.floor(exp))
throw "exponent must be an integer";
if (exp < 0)
return 1 / pow(base, -exp);
var ans = 1;
while (exp > 0) {
ans *= base;
exp--;
}
return ans;
} | 874Exponentiation operator
| 10javascript
| 03qsz |
enum class Fibonacci {
ITERATIVE {
override fun get(n: Int): Long = if (n < 2) {
n.toLong()
} else {
var n1 = 0L
var n2 = 1L
repeat(n) {
val sum = n1 + n2
n1 = n2
n2 = sum
}
n1
}
},
RECURSIVE {
override fun get(n: Int): Long = if (n < 2) n.toLong() else this[n - 1] + this[n - 2]
},
CACHING {
val cache: MutableMap<Int, Long> = mutableMapOf(0 to 0L, 1 to 1L)
override fun get(n: Int): Long = if (n < 2) n.toLong() else impl(n)
private fun impl(n: Int): Long = cache.computeIfAbsent(n) { impl(it-1) + impl(it-2) }
},
;
abstract operator fun get(n: Int): Long
}
fun main() {
val r = 0..30
for (fib in Fibonacci.values()) {
print("${fib.name.padEnd(10)}:")
for (i in r) { print(" " + fib[i]) }
println()
}
} | 862Fibonacci sequence
| 11kotlin
| poib6 |
null | 873Execute HQ9+
| 11kotlin
| geg4d |
class U0 extends Exception { }
class U1 extends Exception { }
public class ExceptionsTest {
public static void foo() throws U1 {
for (int i = 0; i <= 1; i++) {
try {
bar(i);
} catch (U0 e) {
System.out.println("Function foo caught exception U0");
}
}
}
public static void bar(int i) throws U0, U1 {
baz(i); | 876Exceptions/Catch an exception thrown in a nested call
| 9java
| 7w5rj |
function U() {}
U.prototype.toString = function(){return this.className;}
function U0() {
this.className = arguments.callee.name;
}
U0.prototype = new U();
function U1() {
this.className = arguments.callee.name;
}
U1.prototype = new U();
function foo() {
for (var i = 1; i <= 2; i++) {
try {
bar();
}
catch(e if e instanceof U0) {
print("caught exception " + e);
}
}
}
function bar() {
baz();
}
function baz() { | 876Exceptions/Catch an exception thrown in a nested call
| 10javascript
| p8jb7 |
null | 874Exponentiation operator
| 11kotlin
| ksjh3 |
fn main() {
for i in 1..=100 {
match (i% 3, i% 5) {
(0, 0) => println!("fizzbuzz"),
(0, _) => println!("fizz"),
(_, 0) => println!("buzz"),
(_, _) => println!("{}", i),
}
}
} | 835FizzBuzz
| 15rust
| efqaj |
null | 876Exceptions/Catch an exception thrown in a nested call
| 11kotlin
| ubcvc |
function runCode( code )
local acc, lc = 0
for i = 1, #code do
lc = code:sub( i, i ):upper()
if lc == "Q" then print( lc )
elseif lc == "H" then print( "Hello, World!" )
elseif lc == "+" then acc = acc + 1
elseif lc == "9" then
for j = 99, 1, -1 do
if j > 1 then
print( string.format( "%d bottles of beer on the wall\n%d bottles of beer\nTake one down, pass it around\n%d bottles of beer on the wall\n", j, j, j - 1 ) )
else
print( "1 bottle of beer on the wall\n1 bottle of beer\nTake one down and pass it around\nno more bottles of beer on the wall\n\n"..
"No more bottles of beer on the wall\nNo more bottles of beer\n"..
"Go to the store and buy some more\n99 bottles of beer on the wall.\n" )
end
end
end
end
end | 873Execute HQ9+
| 1lua
| rwrga |
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Markov {
public static void main(String[] args) throws IOException {
List<String[]> rules = readRules("markov_rules.txt");
List<String> tests = readTests("markov_tests.txt");
Pattern pattern = Pattern.compile("^([^#]*?)\\s+->\\s+(\\.?)(.*)");
for (int i = 0; i < tests.size(); i++) {
String origTest = tests.get(i);
List<String[]> captures = new ArrayList<>();
for (String rule : rules.get(i)) {
Matcher m = pattern.matcher(rule);
if (m.find()) {
String[] groups = new String[m.groupCount()];
for (int j = 0; j < groups.length; j++)
groups[j] = m.group(j + 1);
captures.add(groups);
}
}
String test = origTest;
String copy = test;
for (int j = 0; j < captures.size(); j++) {
String[] c = captures.get(j);
test = test.replace(c[0], c[2]);
if (c[1].equals("."))
break;
if (!test.equals(copy)) {
j = -1; | 877Execute a Markov algorithm
| 9java
| 86w06 |
local baz_counter=1
function baz()
if baz_counter==1 then
baz_counter=baz_counter+1
error("U0",3) | 876Exceptions/Catch an exception thrown in a nested call
| 1lua
| 5plu6 |
a, b = 1, 0
if (c1:= a == 1) and (c2:= b == 3):
print('a = 1 and b = 3')
elif c1:
print('a = 1 and b <> 3')
elif c2:
print('a <> 1 and b = 3')
else:
print('a <> 1 and b <> 3') | 868Extend your language
| 3python
| 97umf |
islice(count(7), 0, None, 2) | 869Extensible prime generator
| 3python
| lh5cv |
const char target[] = ;
const char tbl[] = ;
int irand(int n)
{
int r, rand_max = RAND_MAX - (RAND_MAX % n);
while((r = rand()) >= rand_max);
return r / (rand_max / n);
}
int unfitness(const char *a, const char *b)
{
int i, sum = 0;
for (i = 0; a[i]; i++)
sum += (a[i] != b[i]);
return sum;
}
void mutate(const char *a, char *b)
{
int i;
for (i = 0; a[i]; i++)
b[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)];
b[i] = '\0';
}
int main()
{
int i, best_i, unfit, best, iters = 0;
char specimen[COPIES][sizeof(target) / sizeof(char)];
for (i = 0; target[i]; i++)
specimen[0][i] = tbl[irand(CHOICE)];
specimen[0][i] = 0;
do {
for (i = 1; i < COPIES; i++)
mutate(specimen[0], specimen[i]);
for (best_i = i = 0; i < COPIES; i++) {
unfit = unfitness(target, specimen[i]);
if(unfit < best || !i) {
best = unfit;
best_i = i;
}
}
if (best_i) strcpy(specimen[0], specimen[best_i]);
printf(, iters++, best, specimen[0]);
} while (best);
return 0;
} | 880Evolutionary algorithm
| 5c
| ga945 |
const markov = ruleSet => {
const splitAt = (s, i) => [s.slice(0, i), s.slice(i)];
const stripLeading = (s, strip) => s.split('')
.filter((e, i) => i >= strip.length).join('');
const replace = (s, find, rep) => {
let result = s;
if (s.indexOf(find) >= 0) {
const a = splitAt(s, s.indexOf(find));
result = [a[0], rep, stripLeading(a[1], find)].join('');
}
return result;
};
const makeRuleMap = ruleset => ruleset.split('\n')
.filter(e => !e.startsWith('#'))
.map(e => e.split(' -> '))
.reduce((p,c) => p.set(c[0], c[1]), new Map());
const parse = (rules, s) => {
const o = s;
for (const [k, v] of rules.entries()) {
if (v.startsWith('.')) {
s = replace(s, k, stripLeading(v, '.'));
break;
} else {
s = replace(s, k, v);
if (s !== o) { break; }
}
}
return o === s ? s : parse(rules, s);
};
const ruleMap = makeRuleMap(ruleSet);
return str => parse(ruleMap, str)
};
const ruleset1 = `# This rules file is extracted from Wikipedia:
# http: | 877Execute a Markov algorithm
| 10javascript
| fl8dg |
package main
import "fmt"
func foo() int {
fmt.Println("let's foo...")
defer func() {
if e := recover(); e != nil {
fmt.Println("Recovered from", e)
}
}()
var a []int
a[12] = 0
fmt.Println("there's no point in going on.")
panic("never reached")
panic(fmt.Scan) | 878Exceptions
| 0go
| sz1qa |
do
throwIO SomeException | 878Exceptions
| 8haskell
| 9rtmo |
number = {}
function number.pow( a, b )
local ret = 1
if b >= 0 then
for i = 1, b do
ret = ret * a.val
end
else
for i = b, -1 do
ret = ret / a.val
end
end
return ret
end
function number.New( v )
local num = { val = v }
local mt = { __pow = number.pow }
setmetatable( num, mt )
return num
end
x = number.New( 5 )
print( x^2 ) | 874Exponentiation operator
| 1lua
| b0hka |
if2 <- function(condition1, condition2, both_true, first_true, second_true, both_false)
{
expr <- if(condition1)
{
if(condition2) both_true else first_true
} else if(condition2) second_true else both_false
eval(expr)
} | 868Extend your language
| 13r
| 35czt |
object FizzBuzz extends App {
1 to 100 foreach { n =>
println((n % 3, n % 5) match {
case (0, 0) => "FizzBuzz"
case (0, _) => "Fizz"
case (_, 0) => "Buzz"
case _ => n
})
}
} | 835FizzBuzz
| 16scala
| q38xw |
null | 877Execute a Markov algorithm
| 11kotlin
| wdbek |
null | 878Exceptions
| 9java
| t28f9 |
null | 877Execute a Markov algorithm
| 1lua
| xfpwz |
function doStuff() {
throw new Error('Not implemented!');
} | 878Exceptions
| 10javascript
| mgfyv |
class HopelesslyEgocentric
def method_missing(what, *args) self end
end
def if2(cond1, cond2)
if cond1 and cond2
yield
HopelesslyEgocentric.new
elsif cond1
Class.new(HopelesslyEgocentric) do
def else1; yield; HopelesslyEgocentric.new end
end.new
elsif cond2
Class.new(HopelesslyEgocentric) do
def else2; yield; HopelesslyEgocentric.new end
end.new
else
Class.new(HopelesslyEgocentric) do
def neither; yield end
end.new
end
end | 868Extend your language
| 14ruby
| lh4cl |
#![allow(unused_variables)]
macro_rules! if2 {
($cond1: expr, $cond2: expr
=> $both:expr
=> $first: expr
=> $second:expr
=> $none:expr)
=> {
match ($cond1, $cond2) {
(true, true) => $both,
(true, _ ) => $first,
(_ , true) => $second,
_ => $none
}
}
}
fn main() {
let i = 1;
let j = 2;
if2!(i > j, i + j >= 3
=> { | 868Extend your language
| 15rust
| 2kglt |
(def c 100)
(def p 0.05)
(def target "METHINKS IT IS LIKE A WEASEL")
(def tsize (count target))
(def alphabet " ABCDEFGHIJLKLMNOPQRSTUVWXYZ") | 880Evolutionary algorithm
| 6clojure
| ksuhs |
sub foo {
foreach (0..1) {
eval { bar($_) };
if ($@ =~ /U0/) { print "Function foo caught exception U0\n"; }
else { die; }
}
}
sub bar {
baz(@_);
}
sub baz {
my $i = shift;
die ($i ? "U1" : "U0");
}
foo(); | 876Exceptions/Catch an exception thrown in a nested call
| 2perl
| 86x0w |
null | 878Exceptions
| 11kotlin
| oyw8z |
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 {
| nt
| }
| }
| }
| }
| }
if2: [A](x: => Boolean)(y: => Boolean)(xyt: => A)java.lang.Object{def else1(xt: => A): java.lang.Object{def else2(yt: =>
A): java.lang.Object{def orElse(nt: => A): A}}} | 868Extend your language
| 16scala
| 51jut |
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') { quinne(@programme) }
when ('9') { bottles() }
default { die "Unknown instruction $char.\n" }
}
}
}
sub hello {
print 'Hello World';
}
sub quinne {
print @programme;
}
sub bottles {
for my $n (reverse 0 .. 99) {
my $before = bottle_count($n);
my $after = bottle_count($n - 1);
my $action = bottle_action($n);
say "\u$before of beer on the wall, $before of beer.";
say "$action, $after of beer on the wall.";
say q() if $n;
}
}
sub bottle_count {
my $n = shift;
given ($n) {
when (-1) { return '99 bottles' }
when (0) { return 'no more bottles' }
when (1) { return '1 bottle' }
default { return "$n bottles" }
}
}
sub bottle_action {
my $n = shift;
return 'Take one down and pass it around' if $n > 0;
return 'Go to the store and buy some more';
} | 873Execute HQ9+
| 2perl
| ncniw |
require
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 | 869Extensible prime generator
| 14ruby
| vbg2n |
@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
my @a = /(.*?)\s+->\s+(\.?)(.*)/ or die "Syntax error: $_";
push @rules, \@a;}
close $source;
my $input = do {local $/; <STDIN>;};
OUTER:
{foreach (@rules)
{my ($from, $terminating, $to) = @$_;
$input =~ s/\Q$from\E/$to/
and ($terminating ? last OUTER : redo OUTER);}}
print $input; | 877Execute a Markov algorithm
| 2perl
| lj6c5 |
class U0(Exception): pass
class U1(Exception): pass
def foo():
for i in range(2):
try:
bar(i)
except U0:
print()
def bar(i):
baz(i)
def baz(i):
raise U1 if i else U0
foo() | 876Exceptions/Catch an exception thrown in a nested call
| 3python
| oyq81 |
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)
}
} | 879Execute a system command
| 0go
| 031sk |
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_while(|&x| x < 150)
.collect::<Vec<_>>());
let diff = count_primes_paged(8000) - count_primes_paged(7700);
println!("There are {} primes between 7,700 and 8,000", diff); | 869Extensible prime generator
| 15rust
| uprvj |
(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-cmd (update-in data [:cells (:ptr data)] (fnil inc 0)))))
(defn dec-cell [next-cmd]
(fn [data]
(next-cmd (update-in data [:cells (:ptr data)] (fnil dec 0)))))
(defn output-cell [next-cmd]
(fn [data]
(set! *output* (conj *output* (get (:cells data) (:ptr data) 0)))
(next-cmd data)))
(defn input-cell [next-cmd]
(fn [data]
(let [[input & rest-input] *input*]
(set! *input* rest-input)
(next-cmd (update-in data [:cells (:ptr data)] input)))))
(defn if-loop [next-cmd loop-cmd]
(fn [data]
(next-cmd (loop [d data]
(if (zero? (get (:cells d) (:ptr d) 0))
d
(recur (loop-cmd d)))))))
(defn terminate [data] data)
(defn split-cmds [cmds]
(letfn [(split [[cmd & rest-cmds] loop-cmds]
(when (nil? cmd) (throw (Exception. )))
(case cmd
\[ (let [[c l] (split-cmds rest-cmds)]
(recur c (str loop-cmds l )))
\] [(apply str rest-cmds) loop-cmds]
(recur rest-cmds (str loop-cmds cmd))))]
(split cmds )))
(defn compile-cmds [[cmd & rest-cmds]]
(if (nil? cmd)
terminate
(case cmd
\> (inc-ptr (compile-cmds rest-cmds))
\< (dec-ptr (compile-cmds rest-cmds))
\+ (inc-cell (compile-cmds rest-cmds))
\- (dec-cell (compile-cmds rest-cmds))
\. (output-cell (compile-cmds rest-cmds))
\, (input-cell (compile-cmds rest-cmds))
\[ (let [[cmds loop-cmds] (split-cmds rest-cmds)]
(if-loop (compile-cmds cmds) (compile-cmds loop-cmds)))
\] (throw (Exception. ))
(compile-cmds rest-cmds))))
(defn compile-and-run [cmds input]
(binding [*input* input *output* []]
(let [compiled-cmds (compile-cmds cmds)]
(println (compiled-cmds (Data. 0 {}))))
(println *output*)
(println (apply str (map char *output*))))) | 881Execute Brain****
| 5c
| 2htlo |
$accumulator = 0;
echo 'HQ9+: ';
$program = trim(fgets(STDIN));
foreach (str_split($program) as $chr) {
switch ($chr) {
case 'H':
case 'h':
printHelloWorld();
break;
case 'Q':
case 'q':
printSource($program);
break;
case '9':
print99Bottles();
break;
case '+':
$accumulator = incrementAccumulator($accumulator);
break;
default:
printError($chr);
}
}
function printHelloWorld() {
echo 'Hello, world!'. PHP_EOL;
}
function printSource($program) {
echo var_export($program, true) . PHP_EOL;
}
function print99Bottles() {
$n = 99;
while($n >= 1) {
echo $n;
echo ' Bottles of Beer on the Wall ';
echo $n;
echo ' bottles of beer, take one down pass it around ';
echo $n-1;
echo ' bottles of beer on the wall.'. PHP_EOL;
$n--;
}
}
function incrementAccumulator($accumulator) {
return ++$accumulator;
}
function printError($chr) {
echo . $chr;
} | 873Execute HQ9+
| 12php
| 7x7rp |
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)
} | 876Exceptions/Catch an exception thrown in a nested call
| 13r
| qtaxs |
error("Something bad happened!") | 878Exceptions
| 1lua
| imxot |
println "ls -la".execute().text | 879Execute a system command
| 7groovy
| enjal |
<?php
function markov($text, $ruleset) {
$lines = explode(PHP_EOL, $ruleset);
$rules = array();
foreach ($lines AS $line) {
$spc = ;
if (empty($line) OR preg_match('/^
continue;
} elseif (preg_match('/^(.+)' . $spc . '->' . $spc . '(\.?)(.*)$/', $line, $matches)) {
list($dummy, $pattern, $terminating, $replacement) = $matches;
$rules[] = array(
'pattern' => trim($pattern),
'terminating' => ($terminating === '.'),
'replacement' => trim($replacement),
);
}
}
do {
$found = false;
foreach ($rules AS $rule) {
if (strpos($text, $rule['pattern']) !== FALSE) {
$text = str_replace($rule['pattern'], $rule['replacement'], $text);
if ($rule['terminating']) {
return $text;
}
$found = true;
break;
}
}
} while($found);
return $text;
}
$conf = array(
1 => array(
'text' => 'I bought a B of As from T S.',
'rule' => '
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
',
),
2 => array(
'text' => 'I bought a B of As from T S.',
'rule' => '
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
',
),
3 => array(
'text' => 'I bought a B of As W my Bgage from T S.',
'rule' => '
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
',
),
4 => array(
'text' => '_1111*11111_',
'rule' => '
_+1 -> _1+
1+1 -> 11+
1! ->!1
,! ->!+
_! -> _
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
1@1 -> x,@y
1@_ -> @_
,@_ ->!_
++ -> +
_1 -> 1
1+_ -> 1
_+_ ->
',
),
5 => array(
'text' => '000000A000000',
'rule' => '
A0 -> 1B
0A1 -> C01
1A1 -> C11
0B0 -> A01
1B0 -> A11
B1 -> 1B
0C0 -> B01
1C0 -> B11
0C1 -> H01
1C1 -> H11
',
),
6 => array(
'text' => '101',
'rule' => '
1 -> 0|
|0 -> 0||
0 ->
',
),
);
foreach ($conf AS $id => $rule) {
echo 'Ruleset ', $id, ': ', markov($rule['text'], $rule['rule']), PHP_EOL;
} | 877Execute a Markov algorithm
| 12php
| qt1x3 |
def foo
2.times do |i|
begin
bar(i)
rescue U0
$stderr.puts
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 | 876Exceptions/Catch an exception thrown in a nested call
| 14ruby
| n90it |
import System.Cmd
main = system "ls" | 879Execute a system command
| 8haskell
| c7t94 |
#[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 in 0..2 {
match bar(i) {
Ok(()) => {},
Err(U::U0(n)) => eprintln!("Caught U0 in foo: {}", n),
Err(e) => return Err(e),
}
}
Ok(())
}
fn main() -> Result<(), U> {
foo()
} | 876Exceptions/Catch an exception thrown in a nested call
| 15rust
| dc8ny |
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 new U1 }
baz(i) | 876Exceptions/Catch an exception thrown in a nested call
| 16scala
| zvntr |
import Foundation
func soeDictOdds() -> UnfoldSequence<Int, Int> {
var bp = 5; var q = 25
var bps: UnfoldSequence<Int, Int>.Iterator? = nil
var dict = [9: 6] | 869Extensible prime generator
| 17swift
| 2k4lj |
(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-cmd (update-in data [:cells (:ptr data)] (fnil inc 0)))))
(defn dec-cell [next-cmd]
(fn [data]
(next-cmd (update-in data [:cells (:ptr data)] (fnil dec 0)))))
(defn output-cell [next-cmd]
(fn [data]
(set! *output* (conj *output* (get (:cells data) (:ptr data) 0)))
(next-cmd data)))
(defn input-cell [next-cmd]
(fn [data]
(let [[input & rest-input] *input*]
(set! *input* rest-input)
(next-cmd (update-in data [:cells (:ptr data)] input)))))
(defn if-loop [next-cmd loop-cmd]
(fn [data]
(next-cmd (loop [d data]
(if (zero? (get (:cells d) (:ptr d) 0))
d
(recur (loop-cmd d)))))))
(defn terminate [data] data)
(defn split-cmds [cmds]
(letfn [(split [[cmd & rest-cmds] loop-cmds]
(when (nil? cmd) (throw (Exception. "invalid commands: missing ]")))
(case cmd
\[ (let [[c l] (split-cmds rest-cmds)]
(recur c (str loop-cmds "[" l "]")))
\] [(apply str rest-cmds) loop-cmds]
(recur rest-cmds (str loop-cmds cmd))))]
(split cmds "")))
(defn compile-cmds [[cmd & rest-cmds]]
(if (nil? cmd)
terminate
(case cmd
\> (inc-ptr (compile-cmds rest-cmds))
\< (dec-ptr (compile-cmds rest-cmds))
\+ (inc-cell (compile-cmds rest-cmds))
\- (dec-cell (compile-cmds rest-cmds))
\. (output-cell (compile-cmds rest-cmds))
\, (input-cell (compile-cmds rest-cmds))
\[ (let [[cmds loop-cmds] (split-cmds rest-cmds)]
(if-loop (compile-cmds cmds) (compile-cmds loop-cmds)))
\] (throw (Exception. "invalid commands: missing ["))
(compile-cmds rest-cmds))))
(defn compile-and-run [cmds input]
(binding [*input* input *output* []]
(let [compiled-cmds (compile-cmds cmds)]
(println (compiled-cmds (Data. 0 {}))))
(println *output*)
(println (apply str (map char *output*))))) | 881Execute Brain****
| 6clojure
| gam4f |
$ loadfile ( if required, the source code for this can be found at
http:
[ stack ] is accumulator ( --> s )
[ stack ] is sourcecode ( --> s )
[ say cr ] is H.HQ9+ ( --> )
[ sourcecode share
echo$ cr ] is Q.HQ9+ ( --> )
[ 99 song echo$ ] is 9.HQ9+ ( --> )
[ 1 accumulator tally ] is +.HQ9+ ( --> )
[ dup sourcecode put
0 accumulator put
witheach
[ $ join
quackery ]
sourcecode release
cr say
accumulator take echo ] is HQ9+ ( $ --> )
$ HQ9+ | 873Execute HQ9+
| 3python
| dldn1 |
import re
def extractreplacements(grammar):
return [ (matchobj.group('pat'), matchobj.group('repl'), bool(matchobj.group('term')))
for matchobj in re.finditer(syntaxre, grammar)
if matchobj.group('rule')]
def replace(text, replacements):
while True:
for pat, repl, term in replacements:
if pat in text:
text = text.replace(pat, repl, 1)
if term:
return text
break
else:
return text
syntaxre = r
grammar1 =
grammar2 = '''\
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
'''
grammar3 = '''\
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
'''
grammar4 = '''\
_+1 -> _1+
1+1 -> 11+
1! ->!1
,! ->!+
_! -> _
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
1@1 -> x,@y
1@_ -> @_
,@_ ->!_
++ -> +
_1 -> 1
1+_ -> 1
_+_ ->
'''
grammar5 = '''\
A0 -> 1B
0A1 -> C01
1A1 -> C11
0B0 -> A01
1B0 -> A11
B1 -> 1B
0C0 -> B01
1C0 -> B11
0C1 -> H01
1C1 -> H11
'''
text1 =
text2 =
text3 = '_1111*11111_'
text4 = '000000A000000'
if __name__ == '__main__':
assert replace(text1, extractreplacements(grammar1)) \
== 'I bought a bag of apples from my brother.'
assert replace(text1, extractreplacements(grammar2)) \
== 'I bought a bag of apples from T shop.'
assert replace(text2, extractreplacements(grammar3)) \
== 'I bought a bag of apples with my money from T shop.'
assert replace(text3, extractreplacements(grammar4)) \
== '11111111111111111111'
assert replace(text4, extractreplacements(grammar5)) \
== '00011H1111000' | 877Execute a Markov algorithm
| 3python
| 2hylz |
enum MyException: ErrorType {
case U0
case U1
}
func foo() throws {
for i in 0 ... 1 {
do {
try bar(i)
} catch MyException.U0 {
print("Function foo caught exception U0")
}
}
}
func bar(i: Int) throws {
try baz(i) | 876Exceptions/Catch an exception thrown in a nested call
| 17swift
| imso0 |
import java.util.Scanner;
import java.io.*;
public class Program {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir"); | 879Execute a system command
| 9java
| zv8tq |
var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause"); | 879Execute a system command
| 10javascript
| 9rfml |
use strict ;
sub expon {
my ( $base , $expo ) = @_ ;
if ( $expo == 0 ) {
return 1 ;
}
elsif ( $expo == 1 ) {
return $base ;
}
elsif ( $expo > 1 ) {
my $prod = 1 ;
foreach my $n ( 0..($expo - 1) ) {
$prod *= $base ;
}
return $prod ;
}
elsif ( $expo < 0 ) {
return 1 / ( expon ( $base , -$expo ) ) ;
}
}
print "3 to the power of 10 as a function is " . expon( 3 , 10 ) . "!\n" ;
print "3 to the power of 10 as a builtin is " . 3**10 . "!\n" ;
print "5.5 to the power of -3 as a function is " . expon( 5.5 , -3 ) . "!\n" ;
print "5.5 to the power of -3 as a builtin is " . 5.5**-3 . "!\n" ; | 874Exponentiation operator
| 2perl
| 3utzs |
factorial()
{
if [ $1 -le 1 ]
then
echo 1
else
result=$(factorial $[$1-1])
echo $((result*$1))
fi
} | 882Factorial
| 4bash
| oyp8a |
use std::env;
fn execute(code: &str) {
let mut accumulator = 0;
for c in code.chars() {
match c {
'Q' => println!(, code),
'H' => println!(),
'9' => {
for n in (1..100).rev() {
println!(, n);
println!(, n);
println!();
if (n - 1) > 1 {
println!(, n - 1);
} else {
println!();
}
}
}
'+' => accumulator += 1,
_ => panic!(, c),
}
}
}
fn main() {
execute(&env::args().nth(1).unwrap());
} | 873Execute HQ9+
| 14ruby
| tvtf2 |
null | 879Execute a system command
| 11kotlin
| imwo4 |
use std::env; | 873Execute HQ9+
| 15rust
| zuzto |
def hq9plus(code: String) : String = {
var out = ""
var acc = 0
def bottle(num: Int) : Unit = {
if (num > 1) {
out += num + " bottles of beer on the wall, " + num + " bottles of beer.\n"
out += "Take one down and pass it around, " + (num - 1) + " bottle"
if (num > 2) out += "s"
out += " of beer.\n\n"
bottle(num - 1)
}
else {
out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
"Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
"No more bottles of beer on the wall, no more bottles of beer.\n" +
"Go to the store and buy some more, 99 bottles of beer on the wall.\n"
}
}
def handle(char: Char) = char match {
case 'H' => out += "Hello world!\n"
case 'Q' => out += code + "\n"
case '+' => acc += 1
case '9' => bottle(99)
}
code.toList foreach handle
out
}
println(hq9plus("HQ9+")) | 873Execute HQ9+
| 16scala
| ygy63 |
def setup(ruleset)
ruleset.each_line.inject([]) do |rules, line|
if line =~ /^\s*
rules
elsif line =~ /^(.+)\s+->\s+(\.?)(.*)$/
rules << [$1, $3, $2!= ]
else
raise
end
end
end
def morcov(ruleset, input_data)
rules = setup(ruleset)
while (matched = rules.find { |match, replace, term|
input_data[match] and input_data.sub!(match, replace)
}) and!matched[2]
end
input_data
end | 877Execute a Markov algorithm
| 14ruby
| ub9vz |
null | 862Fibonacci sequence
| 1lua
| 1inpo |
use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct Rule {
pub pat: String,
pub rep: String,
pub terminal: bool,
}
impl Rule {
pub fn new(pat: String, rep: String, terminal: bool) -> Self {
Self { pat, rep, terminal }
}
pub fn applicable_range(&self, input: impl AsRef<str>) -> Option<std::ops::Range<usize>> {
input
.as_ref()
.match_indices(&self.pat)
.next()
.map(|(start, slice)| start..start + slice.len())
}
pub fn apply(&self, s: &mut String) -> bool {
self.applicable_range(s.as_str()).map_or(false, |range| {
s.replace_range(range, &self.rep);
true
})
}
}
impl FromStr for Rule {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut split = s.splitn(2, " -> ");
let pat = split.next().ok_or_else(|| s.to_string())?;
let rep = split.next().ok_or_else(|| s.to_string())?;
let pat = pat.to_string();
if rep.starts_with('.') {
Ok(Self::new(pat, rep[1..].to_string(), true))
} else {
Ok(Self::new(pat, rep.to_string(), false))
}
}
}
#[derive(Clone, Debug)]
pub struct Rules {
rules: Vec<Rule>,
}
impl Rules {
pub fn new(rules: Vec<Rule>) -> Self {
Self { rules }
}
pub fn apply(&self, s: &mut String) -> Option<&Rule> {
self.rules
.iter()
.find(|rule| rule.apply(s))
}
pub fn execute(&self, mut buffer: String) -> String {
while let Some(rule) = self.apply(&mut buffer) {
if rule.terminal {
break;
}
}
buffer
}
}
impl FromStr for Rules {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut rules = Vec::new();
for line in s.lines().filter(|line|!line.starts_with('#')) {
rules.push(line.parse::<Rule>()?);
}
Ok(Rules::new(rules))
}
}
#[cfg(test)]
mod tests {
use super::Rules;
#[test]
fn case_01() -> Result<(), String> {
let input = "I bought a B of As from T S.";
let rules = "\
# This rules file is extracted from Wikipedia:
# http: | 877Execute a Markov algorithm
| 15rust
| 5pcuq |
import scala.io.Source
object MarkovAlgorithm {
val RulePattern = """(.*?)\s+->\s+(\.?)(.*)""".r
val CommentPattern = """#.*|\s*""".r
def rule(line: String) = line match {
case CommentPattern() => None
case RulePattern(pattern, terminal, replacement) => Some(pattern, replacement, terminal == ".")
case _ => error("Syntax error on line "+line)
}
def main(args: Array[String]) {
if (args.size != 2 ) {
println("Syntax: MarkovAlgorithm inputFile inputPattern")
exit(1)
}
val rules = (Source fromPath args(0) getLines () map rule).toList.flatten
def algorithm(input: String): String = rules find (input contains _._1) match {
case Some((pattern, replacement, true)) => input replaceFirst ("\\Q"+pattern+"\\E", replacement)
case Some((pattern, replacement, false)) => algorithm(input replaceFirst ("\\Q"+pattern+"\\E", replacement))
case None => input
}
println(args(1))
println(algorithm(args(1)))
}
} | 877Execute a Markov algorithm
| 16scala
| revgn |
die "Danger, danger, Will Robinson!";
eval {
die "this could go wrong mightily";
};
print $@ if $@;
die $@; | 878Exceptions
| 2perl
| gal4e |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.