Rosetta Code#
Algorithm implementations from Rosetta Code.
Basic Algorithms#
rosettacode/fizzbuzz.bark
View on GitLab// FizzBuzz
//
// Go implementation: https://rosettacode.org/wiki/FizzBuzz#Go
//
// Print integers 1 to 100. For multiples of 3 print "Fizz",
// for multiples of 5 print "Buzz", for multiples of both print "FizzBuzz".
fn fizzbuzz_label(i int) {
i > math.mod(15) > eq?(0) > return?("FizzBuzz")
i > math.mod(3) > eq?(0) > return?("Fizz")
i > math.mod(5) > eq?(0) > return?("Buzz")
i > to_string() > result
return(result)
}(string)
fn print_fizzbuzz(arr array, idx int) {
arr > get(idx) > i
i > fizzbuzz_label() > label
print("{0} ", label)
}()
// Run FizzBuzz for 1 to 100
array.range(1, 100) > each(print_fizzbuzz)
println()
rosettacode/factorial.bark
View on GitLab// Factorial
//
// Go implementation: https://rosettacode.org/wiki/Factorial#Go
//
// Calculate the factorial of a number: n! = n × (n-1) × ... × 1
// For example: 5! = 5 × 4 × 3 × 2 × 1 = 120
// Factorial using tail recursion with accumulator
fn factorial(n int) {
// Use tuple to initialize (num, acc) for recursive anonymous function
// n! = n * (n-1) * (n-2) * ... * 1
// 0! = 1 and 1! = 1 (base cases handled by lte?(1))
(n, 1) > (num int, acc int) {
num > lte?(1) > return?(acc)
num > sub(1) > next_num
acc > mul(num) > next_acc
repeat(next_num, next_acc)
}(int) > result
return(result)
}(int)
// Print factorial results for 0 to 12
fn print_factorial(arr array, idx int) {
arr > get(idx) > n
n > factorial() > result
println("{0}! = {1}", n, result)
}()
array.range(0, 12) > each(print_factorial)
rosettacode/fibonacci.bark
View on GitLab// Fibonacci Sequence
//
// Go implementation: https://rosettacode.org/wiki/Fibonacci_sequence#Go
//
// Generate Fibonacci numbers: F(n) = F(n-1) + F(n-2)
// where F(0) = 0 and F(1) = 1
// Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
// Iterative Fibonacci using tail recursion pattern
fn fibonacci(n int) {
n > lte?(0) > return?(0)
n > eq?(1) > return?(1)
// Use tuple (target, current_idx, prev, curr) for iteration
// At step i: prev = F(i-1), curr = F(i)
// We compute F(i+1) = prev + curr
(n, 2, 0, 1) > (target int, i int, prev int, curr int) {
// Compute next Fibonacci number
prev > add(curr) > next_val
// When i reaches target, return the computed value
i > gte?(target) > return?(next_val)
i > add(1) > next_i
repeat(target, next_i, curr, next_val)
}(int) > result
return(result)
}(int)
fn print_fib(arr array, idx int) {
arr > get(idx) > n
n > fibonacci() > result
println("F({0}) = {1}", n, result)
}()
// Print first 21 Fibonacci numbers (F(0) to F(20))
array.range(0, 20) > each(print_fib)
rosettacode/even_odd.bark
View on GitLab// Even or Odd
//
// Go implementation: https://rosettacode.org/wiki/Even_or_odd#Go
//
// Determine if an integer is even or odd.
// Demonstrates using the math module's even?() and odd?() functions.
fn parity_label(n int) {
n > math.even?() > return?("even")
return("odd")
}(string)
fn print_parity(n int) {
n > parity_label() > label
println("{0} is {1}", n, label)
}()
// Test positive numbers
println("Positive numbers:")
0 > print_parity()
1 > print_parity()
2 > print_parity()
3 > print_parity()
10 > print_parity()
11 > print_parity()
100 > print_parity()
101 > print_parity()
println()
// Test negative numbers
println("Negative numbers:")
-1 > print_parity()
-2 > print_parity()
-3 > print_parity()
-4 > print_parity()
-99 > print_parity()
-100 > print_parity()
println()
// Demonstrate using both math.even?() and math.odd?()
println("Using math.even?() and math.odd?():")
42 > (n int) {
n > math.even?() > is_even
n > math.odd?() > is_odd
println("{0}: even?={1}, odd?={2}", n, is_even, is_odd)
}()
17 > (n int) {
n > math.even?() > is_even
n > math.odd?() > is_odd
println("{0}: even?={1}, odd?={2}", n, is_even, is_odd)
}()
Math#
rosettacode/abs.bark
View on GitLab// Absolute Value
//
// Go implementation: https://rosettacode.org/wiki/Absolute_value#Go
//
// Return the absolute value of a number.
// Demonstrates using the math.abs() function.
fn print_abs(n int) {
n > math.abs() > result
println("|{0}| = {1}", n, result)
}()
fn print_abs_float(n float) {
n > math.abs() > result
println("|{0}| = {1}", n, result)
}()
println("Integer absolute values:")
0 > print_abs()
1 > print_abs()
-1 > print_abs()
42 > print_abs()
-42 > print_abs()
100 > print_abs()
-100 > print_abs()
println()
println("Floating-point absolute values:")
0.0 > print_abs_float()
3.14 > print_abs_float()
-3.14 > print_abs_float()
2.718 > print_abs_float()
-2.718 > print_abs_float()
0.001 > print_abs_float()
-0.001 > print_abs_float()
rosettacode/gcd.bark
View on GitLab// Greatest Common Divisor (GCD)
//
// Go implementation: https://rosettacode.org/wiki/Greatest_common_divisor#Go
//
// Find the greatest common divisor of two numbers using Euclidean algorithm.
// Common use case: simplifying fractions, scheduling, cryptography (RSA).
fn gcd(a int, b int) {
b > eq?(0) > return?(a)
a > math.mod(b) > remainder
repeat(b, remainder)
}(int)
fn print_gcd(a int, b int) {
a > gcd(b) > result
println("gcd({0}, {1}) = {2}", a, b, result)
}()
// Test cases
12 > print_gcd(8)
54 > print_gcd(24)
48 > print_gcd(18)
100 > print_gcd(35)
17 > print_gcd(13)
1071 > print_gcd(462)
0 > print_gcd(5)
5 > print_gcd(0)
rosettacode/lcm.bark
View on GitLab// Least Common Multiple (LCM)
//
// Go implementation: https://rosettacode.org/wiki/Least_common_multiple#Go
//
// Find the least common multiple of two integers.
// LCM(a, b) = |a * b| / GCD(a, b)
// Greatest Common Divisor using Euclidean algorithm
fn gcd(a int, b int) {
b > eq?(0) > return?(a)
a > math.mod(b) > remainder
repeat(b, remainder)
}(int)
// Least Common Multiple
fn lcm(a int, b int) {
// Handle zero case
a > eq?(0) > return?(0)
b > eq?(0) > return?(0)
// LCM = |a * b| / GCD(a, b)
a > mul(b) > math.abs() > product
a > gcd(b) > divisor
product > div(divisor) > math.to_int() > result
return(result)
}(int)
fn print_lcm(a int, b int) {
a > lcm(b) > result
println("lcm({0}, {1}) = {2}", a, b, result)
}()
// Test cases
12 > print_lcm(8)
21 > print_lcm(6)
4 > print_lcm(6)
15 > print_lcm(20)
18 > print_lcm(24)
0 > print_lcm(5)
5 > print_lcm(0)
7 > print_lcm(7)
12 > print_lcm(18)
rosettacode/prime.bark
View on GitLab// Prime Number Check
//
// Go implementation: https://rosettacode.org/wiki/Primality_by_trial_division#Go
//
// Check if a number is prime using trial division.
// Common use case: cryptography, number theory, security applications.
fn check_divisors(i int, limit int, n int) {
i > gt?(limit) > return?(true)
n > math.mod(i) > eq?(0) > return?(false)
i > add(2) > next_i
repeat(next_i, limit, n)
}(bool)
fn is_prime(n int) {
// Numbers less than 2 are not prime
n > lt?(2) > return?(false)
// 2 is prime
n > eq?(2) > return?(true)
// Even numbers greater than 2 are not prime
n > math.even?() > return?(false)
// Check odd divisors from 3 up to sqrt(n)
n > math.sqrt() > math.to_int() > limit
3 > check_divisors(limit, n) > result
return(result)
}(bool)
fn prime_label(n int) {
n > is_prime() > return?("is prime")
return("is not prime")
}(string)
fn print_result(n int) {
n > prime_label() > label
println("{0} {1}", n, label)
}()
// Test cases
1 > print_result()
2 > print_result()
3 > print_result()
4 > print_result()
5 > print_result()
6 > print_result()
7 > print_result()
10 > print_result()
11 > print_result()
13 > print_result()
17 > print_result()
19 > print_result()
20 > print_result()
23 > print_result()
97 > print_result()
100 > print_result()
rosettacode/sum_digits.bark
View on GitLab// Sum of Digits
//
// Go implementation: https://rosettacode.org/wiki/Sum_of_digits_of_an_integer#Go
//
// Calculate the sum of digits of a non-negative integer.
// Can work in any base (default base 10).
// Sum digits in base 10
fn sum_digits(n int) {
n > math.abs() > math.to_int() > abs_n
(0, abs_n) > (sum int, num int) {
num > eq?(0) > return?(sum)
num > math.mod(10) > math.to_int() > digit
sum > add(digit) > new_sum
num > div(10) > math.to_int() > next_num
repeat(new_sum, next_num)
}(int) > result
return(result)
}(int)
// Sum digits in arbitrary base
fn sum_digits_base(n int, base int) {
n > math.abs() > math.to_int() > abs_n
(0, abs_n) > (sum int, num int) {
num > eq?(0) > return?(sum)
num > math.mod(base) > math.to_int() > digit
sum > add(digit) > new_sum
num > div(base) > math.to_int() > next_num
repeat(new_sum, next_num)
}(int) > result
return(result)
}(int)
fn print_sum(n int) {
n > sum_digits() > result
println("Sum of digits of {0} = {1}", n, result)
}()
fn print_sum_base(n int, base int) {
n > sum_digits_base(base) > result
println("Sum of digits of {0} (base {1}) = {2}", n, base, result)
}()
println("Base 10 digit sums:")
0 > print_sum()
1 > print_sum()
12 > print_sum()
123 > print_sum()
1234 > print_sum()
9999 > print_sum()
println()
println("Larger numbers:")
12345 > print_sum()
999999 > print_sum()
1000000 > print_sum()
println()
// Rosetta Code examples
println("Rosetta Code examples:")
1 > print_sum()
12345 > print_sum()
123045 > print_sum()
println()
println("Different bases:")
// 0xfe (254 in decimal) in base 16: f=15, e=14, sum=29
254 > print_sum_base(16)
// 0x7fff (32767) in base 16: 7+f+f+f = 7+15+15+15 = 52
32767 > print_sum_base(16)
// Binary: 255 = 11111111, sum = 8
255 > print_sum_base(2)
// Octal: 64 = 100 in octal, sum = 1
64 > print_sum_base(8)
rosettacode/sum_array.bark
View on GitLab// Sum of Array
//
// Go implementation: https://rosettacode.org/wiki/Sum_of_a_series#Go
//
// Calculate the sum of all elements in an array.
// Common use case: data aggregation, statistics, reporting, totals.
fn sum_helper(idx int, acc int, arr array, length int) {
idx > gte?(length) > return?(acc)
arr > get(idx) > val
acc > add(val) > new_acc
idx > add(1) > next_idx
repeat(next_idx, new_acc, arr, length)
}(int)
fn sum(arr array) {
arr > len() > length
0 > sum_helper(0, arr, length) > result
return(result)
}(int)
fn print_sum(arr array) {
arr > sum() > result
println("sum({0}) = {1}", arr, result)
}()
// Test cases
[1, 2, 3, 4, 5] > print_sum()
[10, 20, 30] > print_sum()
[100] > print_sum()
[] > print_sum()
[-5, 5, -10, 10] > print_sum()
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > print_sum()
Strings#
rosettacode/reverse_string.bark
View on GitLab// Reverse a String
//
// Go implementation: https://rosettacode.org/wiki/Reverse_a_string#Go
//
// Reverse the characters in a string.
// Test cases - reverse() works directly on strings
fn print_test(original string) {
original > reverse() > reversed
print(original)
print(" -> ")
print(reversed)
print("\n")
}()
// Test with various strings
"hello" > print_test()
"world" > print_test()
"bark" > print_test()
"12345" > print_test()
"racecar" > print_test()
"a" > print_test()
"" > print_test()
rosettacode/palindrome.bark
View on GitLab// Palindrome Detection
//
// Go implementation: https://rosettacode.org/wiki/Palindrome_detection#Go
//
// Check if a string reads the same forwards and backwards.
// Common use case: input validation, word games, data verification.
fn is_palindrome(s string) {
s > str.lower() > normalized
normalized > reverse() > reversed
normalized > eq?(reversed) > result
return(result)
}(bool)
fn palindrome_label(s string) {
s > is_palindrome() > return?("is a palindrome")
return("is not a palindrome")
}(string)
fn print_result(s string) {
s > palindrome_label() > label
println("\"{0}\" {1}", s, label)
}()
// Test cases
"racecar" > print_result()
"level" > print_result()
"hello" > print_result()
"A" > print_result()
"Madam" > print_result()
"noon" > print_result()
"world" > print_result()
"" > print_result()
rosettacode/count_occurrences.bark
View on GitLab// Count Occurrences of a Substring
//
// Go implementation: https://rosettacode.org/wiki/Count_occurrences_of_a_substring#Go
//
// Count how many times a substring appears in a string.
// Common use case: text analysis, search, logging analysis, word frequency.
fn count_occurrences(haystack string, needle string) {
haystack > str.split(needle) > parts
parts > len() > num_parts
num_parts > sub(1) > count
return(count)
}(int)
fn print_count(haystack string, needle string) {
haystack > count_occurrences(needle) > count
println("\"{0}\" appears {1} time(s) in \"{2}\"", needle, count, haystack)
}()
// Test cases
"the three truths" > print_count("th")
"ababababab" > print_count("abab")
"aaaaaa" > print_count("aa")
"hello world" > print_count("o")
"mississippi" > print_count("ss")
"abcdef" > print_count("xyz")
"" > print_count("test")
rosettacode/is_numeric.bark
View on GitLab// Determine if a String is Numeric
//
// Go implementation: https://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Go
//
// Check if a string represents a valid numeric value.
// Uses the str.numeric? builtin which supports integers, floats,
// negative numbers, and scientific notation.
fn numeric_label(s string) {
s > str.numeric?() > return?("is numeric")
return("is NOT numeric")
}(string)
fn print_result(s string) {
s > numeric_label() > label
println("\"{0}\" {1}", s, label)
}()
// Test cases
println("Integer tests:")
"123" > print_result()
"0" > print_result()
"-456" > print_result()
"42" > print_result()
println()
println("Float tests:")
"3.14" > print_result()
"-2.718" > print_result()
"0.5" > print_result()
"123." > print_result()
println()
println("Invalid inputs:")
"" > print_result()
"hello" > print_result()
"12.34.56" > print_result()
"-" > print_result()
"1a2b" > print_result()
" " > print_result()
"12 34" > print_result()
println()
println("Edge cases:")
" 42 " > print_result()
"007" > print_result()
"-0" > print_result()
rosettacode/caesar_cipher.bark
View on GitLab// Caesar Cipher
//
// Go implementation: https://rosettacode.org/wiki/Caesar_cipher#Go
//
// Encrypt and decrypt text using Caesar cipher.
// Each letter is shifted by a fixed number of positions in the alphabet.
// Find index of character in alphabet string, returns -1 if not found
fn find_char_index(alpha string, c string) {
alpha > str.split("") > chars
chars > len() > length
(0) > (idx int) {
idx > gte?(length) > return?(-1)
chars > get(idx) > ch
ch > eq?(c) > return?(idx)
idx > add(1) > next
repeat(next)
}(int) > result
return(result)
}(int)
// Get character at position in alphabet
fn get_char_at(alpha string, pos int) {
alpha > str.split("") > chars
chars > get(pos) > result
return(result)
}(string)
// Shift a single character by n positions
// Only shifts A-Z and a-z, leaves other characters unchanged
fn shift_char(c string, n int) {
c > eq?("") > return?("")
// Build uppercase and lowercase alphabets
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" > upper_alpha
"abcdefghijklmnopqrstuvwxyz" > lower_alpha
// Check uppercase
upper_alpha > find_char_index(c) > upper_pos
upper_pos > gte?(0) > (is_upper bool) {
is_upper > eq?(false) > return?()
upper_pos > add(n) > add(26) > math.mod(26) > new_pos
upper_alpha > get_char_at(new_pos) > shifted
return(shifted)
}(string) > upper_result
upper_result > present?() > return?(upper_result)
// Check lowercase
lower_alpha > find_char_index(c) > lower_pos
lower_pos > gte?(0) > (is_lower bool) {
is_lower > eq?(false) > return?()
lower_pos > add(n) > add(26) > math.mod(26) > new_pos
lower_alpha > get_char_at(new_pos) > shifted
return(shifted)
}(string) > lower_result
lower_result > present?() > return?(lower_result)
// Not a letter, return unchanged
return(c)
}(string)
// Encrypt a string with Caesar cipher
fn caesar_encrypt(text string, shift int) {
text > str.split("") > chars
chars > len() > length
("", 0) > (result string, idx int) {
idx > gte?(length) > return?(result)
chars > get(idx) > c
c > shift_char(shift) > shifted
result > str.concat(shifted) > new_result
idx > add(1) > next_idx
repeat(new_result, next_idx)
}(string) > encrypted
return(encrypted)
}(string)
// Decrypt by shifting in opposite direction
fn caesar_decrypt(text string, shift int) {
0 > sub(shift) > neg_shift
text > caesar_encrypt(neg_shift) > result
return(result)
}(string)
// Test the cipher
"The Quick Brown Fox Jumps Over The Lazy Dog" > original
println("Original: {0}", original)
original > caesar_encrypt(13) > encrypted
println("Encrypted (ROT13): {0}", encrypted)
encrypted > caesar_decrypt(13) > decrypted
println("Decrypted: {0}", decrypted)
println()
// Test with different shift values
"HELLO WORLD" > msg
println("Message: {0}", msg)
msg > caesar_encrypt(3) > enc3
println("Shift 3: {0}", enc3)
enc3 > caesar_decrypt(3) > dec3
println("Decrypt: {0}", dec3)
rosettacode/anagram.bark
View on GitLab// Anagram Detection
//
// Go implementation: https://rosettacode.org/wiki/Anagrams#Go
//
// Check if two strings are anagrams of each other.
// Two words are anagrams if they contain the same letters in different order.
//
// We use character counting instead of sorting - count occurrences of each
// character in both strings and compare the counts.
// Count character frequencies in a string, returning a map
fn char_counts(s string) {
// Remove spaces first, then split
s > str.lower() > str.replace(" ", "") > cleaned
cleaned > str.split("") > chars
chars > len() > length
({}, 0) > (counts map, idx int) {
idx > gte?(length) > return?(counts)
chars > get(idx) > c
// Get current count (default 0) and increment
counts > map.get_or(c, 0) > current
current > add(1) > new_count
counts > set(c, new_count) > new_counts
idx > add(1) > next_idx
repeat(new_counts, next_idx)
}(map) > result
return(result)
}(map)
// Compare two maps for equality
fn maps_equal(a map, b map) {
a > size() > len_a
b > size() > len_b
len_a > neq?(len_b) > return?(false)
// Check each key in a exists in b with same value
a > map.keys() > a_keys
a_keys > len() > num_keys
(0) > (idx int) {
idx > gte?(num_keys) > return?(true)
a_keys > get(idx) > key
a > get(key) > a_val
b > map.get_or(key, -1) > b_val
a_val > neq?(b_val) > return?(false)
idx > add(1) > next
repeat(next)
}(bool) > result
return(result)
}(bool)
// Check if two strings are anagrams
fn is_anagram(a string, b string) {
a > char_counts() > counts_a
b > char_counts() > counts_b
counts_a > maps_equal(counts_b) > result
return(result)
}(bool)
fn anagram_label(a string, b string) {
a > is_anagram(b) > return?("are anagrams")
return("are NOT anagrams")
}(string)
fn print_result(a string, b string) {
a > anagram_label(b) > label
println("\"{0}\" and \"{1}\" {2}", a, b, label)
}()
// Test cases
"listen" > print_result("silent")
"evil" > print_result("vile")
"dormitory" > print_result("dirty room")
"hello" > print_result("world")
"astronomer" > print_result("moon starer")
"the eyes" > print_result("they see")
"abc" > print_result("cab")
"abc" > print_result("abd")
"" > print_result("")
"a" > print_result("a")
rosettacode/balanced_brackets.bark
View on GitLab// Balanced Brackets
//
// Go implementation: https://rosettacode.org/wiki/Balanced_brackets#Go
//
// Check if a string of brackets is balanced.
// Each opening bracket must have a matching closing bracket.
// Helper to compute new count based on character
fn update_count(char string, count int) {
count > add(1) > inc
count > sub(1) > dec
char > eq?("[") > return?(inc)
char > eq?("]") > return?(dec)
return(count)
}(int)
// Check if brackets are balanced using a counter
// For each '[' increment, for each ']' decrement
// Balanced if counter never goes negative and ends at 0
fn is_balanced(s string) {
s > len() > length
length > eq?(0) > return?(true)
// Split string into characters and check balance
s > str.split("") > chars
(0, 0) > (idx int, count int) {
// Check if we've processed all characters - return whether count is 0
idx > gte?(length) > done
count > eq?(0) > is_zero
done > return?(is_zero)
chars > get(idx) > char
char > update_count(count) > new_count
// If count goes negative, we have too many closing brackets
new_count > lt?(0) > return?(false)
idx > add(1) > next_idx
repeat(next_idx, new_count)
}(bool) > result
return(result)
}(bool)
fn balance_label(s string) {
s > is_balanced() > return?("balanced")
return("not balanced")
}(string)
fn print_result(s string) {
s > balance_label() > label
s > len() > slen
slen > eq?(0) > (is_empty bool) {
is_empty > return?("(empty)")
return(s)
}(string) > display
println("\"{0}\" is {1}", display, label)
}()
// Test cases
"" > print_result()
"[]" > print_result()
"[][]" > print_result()
"[[]]" > print_result()
"[[][]]" > print_result()
"][" > print_result()
"][][" > print_result()
"[]][[]" > print_result()
"[[" > print_result()
"]]" > print_result()
"[[]" > print_result()
"[]]" > print_result()
"[[[]]]" > print_result()
"[[]][[]]" > print_result()
Arrays#
rosettacode/array_length.bark
View on GitLab// Array Length
//
// Go implementation: https://rosettacode.org/wiki/Array_length#Go
//
// Determine the length/size of an array.
// Demonstrates using len() and size() functions.
fn print_length(arr array) {
arr > len() > length
println("Array {0} has length {1}", arr, length)
}()
println("Array length examples:")
println()
// Various array sizes
[] > print_length()
[1] > print_length()
[1, 2] > print_length()
[1, 2, 3] > print_length()
[1, 2, 3, 4, 5] > print_length()
println()
// String arrays
["hello"] > print_length()
["hello", "world"] > print_length()
["a", "b", "c", "d", "e", "f"] > print_length()
println()
// Mixed types
[1, "two", 3, "four"] > print_length()
[true, false, true] > print_length()
println()
// Nested arrays
[[1, 2], [3, 4], [5, 6]] > nested
nested > len() > nested_len
println("Nested array {0} has length {1}", nested, nested_len)
// Length of inner arrays
nested > get(0) > first_inner
first_inner > len() > inner_len
println("First inner array {0} has length {1}", first_inner, inner_len)
println()
// size() is an alias for len()
println("Using size() as alias for len():")
[1, 2, 3, 4] > arr
arr > size() > s
println("size([1, 2, 3, 4]) = {0}", s)
rosettacode/array_concat.bark
View on GitLab// Array Concatenation
//
// Go implementation: https://rosettacode.org/wiki/Array_concatenation#Go
//
// Concatenate two arrays.
// Demonstrates using array.append_to() to join arrays.
fn print_array(arr array) {
arr > to_string() > println()
}()
println("Array concatenation examples:")
println()
// Basic concatenation
[1, 2, 3] > a
[4, 5, 6] > b
println("Array a: {0}", a)
println("Array b: {0}", b)
// Concatenate b onto a
a > array.append_to(b) > result
println("a concatenated with b: {0}", result)
println()
// Concatenate strings
["hello", "world"] > s1
["foo", "bar", "baz"] > s2
s1 > array.append_to(s2) > s_concat
println("String arrays: {0}", s_concat)
println()
// Empty array concatenation
[] > empty
[1, 2, 3] > numbers
empty > array.append_to(numbers) > from_empty
println("Empty + [1,2,3]: {0}", from_empty)
numbers > array.append_to([]) > to_empty
println("[1,2,3] + Empty: {0}", to_empty)
println()
// Multiple concatenations
[1] > one
[2] > two
[3] > three
one > array.append_to(two) > array.append_to(three) > chained
println("Chained [1] + [2] + [3]: {0}", chained)
rosettacode/remove_duplicates.bark
View on GitLab// Remove Duplicate Elements
//
// Go implementation: https://rosettacode.org/wiki/Remove_duplicate_elements#Go
//
// Remove duplicate elements from an array, keeping only unique values.
// Common use case: data cleaning, deduplication, unique lists.
fn print_unique(arr array) {
arr > array.dedupe() > unique
println("original: {0}", arr)
println(" unique: {0}\n", unique)
}()
// Test cases
[1, 2, 3, 1, 2, 3] > print_unique()
[1, 1, 1, 1] > print_unique()
[1, 2, 3, 4, 5] > print_unique()
[] > print_unique()
[5, 4, 3, 2, 1, 1, 2, 3, 4, 5] > print_unique()
[42] > print_unique()
rosettacode/max_min.bark
View on GitLab// Find Maximum and Minimum
//
// Go implementation: https://rosettacode.org/wiki/Greatest_element_of_a_list#Go
//
// Find the maximum and minimum elements in an array.
// Common use case: data analysis, validation, range checking.
fn max_helper(idx int, max_val int, arr array, length int) {
idx > gte?(length) > return?(max_val)
arr > get(idx) > val
max_val > math.max(val) > new_max
idx > add(1) > next_idx
repeat(next_idx, new_max, arr, length)
}(int)
fn min_helper(idx int, min_val int, arr array, length int) {
idx > gte?(length) > return?(min_val)
arr > get(idx) > val
min_val > math.min(val) > new_min
idx > add(1) > next_idx
repeat(next_idx, new_min, arr, length)
}(int)
fn find_max(arr array) {
arr > len() > length
length > eq?(0) > return?(0)
arr > get(0) > first
1 > max_helper(first, arr, length) > result
return(result)
}(int)
fn find_min(arr array) {
arr > len() > length
length > eq?(0) > return?(0)
arr > get(0) > first
1 > min_helper(first, arr, length) > result
return(result)
}(int)
fn print_max_min(arr array) {
arr > find_max() > max_val
arr > find_min() > min_val
println("array: {0}", arr)
println(" max: {0}", max_val)
println(" min: {0}\n", min_val)
}()
// Test cases
[3, 1, 4, 1, 5, 9, 2, 6] > print_max_min()
[10, 20, 30, 40, 50] > print_max_min()
[50, 40, 30, 20, 10] > print_max_min()
[-5, -2, -8, -1] > print_max_min()
[42] > print_max_min()
[7, 7, 7, 7] > print_max_min()
Miscellaneous#
rosettacode/leap_year.bark
View on GitLab// Leap Year
//
// Go implementation: https://rosettacode.org/wiki/Leap_year#Go
//
// Determine if a year is a leap year.
// Common use case: calendar applications, date validation, scheduling.
//
// Rules:
// - Divisible by 4 AND not divisible by 100, OR
// - Divisible by 400
fn is_leap_year(year int) {
// Divisible by 400 -> leap year
year > math.mod(400) > eq?(0) > return?(true)
// Divisible by 100 but not 400 -> not leap year
year > math.mod(100) > eq?(0) > return?(false)
// Divisible by 4 -> leap year
year > math.mod(4) > eq?(0) > return?(true)
// Otherwise -> not leap year
return(false)
}(bool)
fn leap_year_label(year int) {
year > is_leap_year() > return?("is a leap year")
return("is not a leap year")
}(string)
fn print_result(year int) {
year > leap_year_label() > label
println("{0} {1}", year, label)
}()
// Test cases
1900 > print_result()
2000 > print_result()
2020 > print_result()
2021 > print_result()
2024 > print_result()
2100 > print_result()
1600 > print_result()
1700 > print_result()
rosettacode/temperature.bark
View on GitLab// Temperature Conversion
//
// Go implementation: https://rosettacode.org/wiki/Temperature_conversion#Go
//
// Convert temperatures between Celsius, Fahrenheit, and Kelvin.
// Common use case: weather apps, scientific calculations, IoT sensors.
fn celsius_to_fahrenheit(c float) {
c > mul(9.0) > div(5.0) > add(32.0) > result
return(result)
}(float)
fn fahrenheit_to_celsius(f float) {
f > sub(32.0) > mul(5.0) > div(9.0) > result
return(result)
}(float)
fn celsius_to_kelvin(c float) {
c > add(273.15) > result
return(result)
}(float)
fn kelvin_to_celsius(k float) {
k > sub(273.15) > result
return(result)
}(float)
fn print_celsius(c float) {
c > celsius_to_fahrenheit() > f
c > celsius_to_kelvin() > k
println("{0} C = {1} F = {2} K", c, f, k)
}()
fn print_fahrenheit(f float) {
f > fahrenheit_to_celsius() > c
println("{0} F = {1} C", f, c)
}()
// Test Celsius conversions
print("Celsius conversions:\n")
0.0 > print_celsius()
100.0 > print_celsius()
-40.0 > print_celsius()
37.0 > print_celsius()
// Test Fahrenheit to Celsius
print("\nFahrenheit to Celsius:\n")
32.0 > print_fahrenheit()
212.0 > print_fahrenheit()
-40.0 > print_fahrenheit()
98.6 > print_fahrenheit()
rosettacode/binary_digits.bark
View on GitLab// Binary Digits
//
// Go implementation: https://rosettacode.org/wiki/Binary_digits#Go
//
// Convert a non-negative integer to its binary representation.
// Helper for binary conversion iteration
fn binary_iter(result string, num int) {
num > eq?(0) > done
done > return?(result)
num > math.mod(2) > to_string() > bit
bit > str.concat(result) > new_result
num > div(2) > math.to_int() > next_num
repeat(new_result, next_num)
}(string)
// Convert integer to binary string
fn to_binary(n int) {
n > eq?(0) > return?("0")
// Build binary string by repeatedly dividing by 2
"" > binary_iter(n) > binary
return(binary)
}(string)
fn print_binary(n int) {
n > to_binary() > binary
println("{0} in binary is {1}", n, binary)
}()
// Test cases from Rosetta Code
0 > print_binary()
1 > print_binary()
2 > print_binary()
3 > print_binary()
4 > print_binary()
5 > print_binary()
6 > print_binary()
7 > print_binary()
8 > print_binary()
9 > print_binary()
10 > print_binary()
15 > print_binary()
16 > print_binary()
42 > print_binary()
255 > print_binary()
256 > print_binary()
1000 > print_binary()
rosettacode/100_doors.bark
View on GitLab// 100 Doors
//
// Go implementation: https://rosettacode.org/wiki/100_doors#Go
//
// Problem: There are 100 doors in a row, initially all closed.
// You make 100 passes. On pass i, you toggle every i-th door.
// Which doors are open after 100 passes?
//
// Answer: Doors that are perfect squares (1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
// because only perfect squares have an odd number of divisors.
// Initialize array of 100 doors (all false = closed)
fn init_doors() {
([], 1) > (doors array, i int) {
i > gt?(100) > return?(doors)
doors > array.push(false) > new_doors
i > add(1) > next
repeat(new_doors, next)
}(array) > result
return(result)
}(array)
// Toggle door at index (0-based)
fn toggle_door(doors array, idx int) {
doors > get(idx) > current
current > not() > toggled
doors > set(idx, toggled) > result
return(result)
}(array)
// Run pass k: toggle every k-th door (1-indexed doors, so toggle indices k-1, 2k-1, 3k-1, ...)
fn run_pass(doors array, k int) {
(doors, k) > (d array, idx int) {
idx > gt?(100) > return?(d)
// idx is 1-indexed door number, array is 0-indexed
idx > sub(1) > arr_idx
d > toggle_door(arr_idx) > new_doors
idx > add(k) > next_idx
repeat(new_doors, next_idx)
}(array) > result
return(result)
}(array)
// Run all 100 passes
fn run_all_passes(doors array) {
(doors, 1) > (d array, pass int) {
pass > gt?(100) > return?(d)
d > run_pass(pass) > new_doors
pass > add(1) > next_pass
repeat(new_doors, next_pass)
}(array) > result
return(result)
}(array)
// Print open doors
fn print_open_doors(doors array) {
println("Open doors after 100 passes:")
(1) > (door_num int) {
door_num > gt?(100) > return?()
// Check if door is open (array is 0-indexed)
door_num > sub(1) > arr_idx
doors > get(arr_idx) > is_open
is_open > println?("Door {0} is open", door_num)
door_num > add(1) > next
repeat(next)
}()
}()
// Main execution
init_doors() > run_all_passes() > print_open_doors()
println()
println("These are the perfect squares from 1 to 100:")
println("1, 4, 9, 16, 25, 36, 49, 64, 81, 100")
rosettacode/bottles.bark
View on GitLab// 99 Bottles of Beer
//
// Go implementation: https://rosettacode.org/wiki/99_bottles_of_beer#Go
//
// Print the lyrics to "99 Bottles of Beer on the Wall"
fn bottle_word(n int) {
n > eq?(1) > return?("bottle")
return("bottles")
}(string)
fn print_verse(n int) {
n > bottle_word() > word
println("{0} {1} of beer on the wall,", n, word)
println("{0} {1} of beer.", n, word)
println("Take one down, pass it around,")
println()
n > sub(1) > remaining
remaining > eq?(0) > println?("No more bottles of beer on the wall.") > return()
remaining > bottle_word() > next_word
println("{0} {1} of beer on the wall.", remaining, next_word)
println()
}()
fn count_down(n int) {
n > lt?(1) > return?()
n > print_verse()
n > sub(1) > next
repeat(next)
}()
// Sing from 99 down to 1
99 > count_down()
rosettacode/ackermann.bark
View on GitLab// Ackermann Function (Memoized)
//
// Go implementation: https://rosettacode.org/wiki/Ackermann_function#Go
//
// The Ackermann function is a classic example of a total computable function
// that is not primitive recursive. It grows extremely fast.
//
// A(m, n) =
// n + 1 if m = 0
// A(m-1, 1) if m > 0 and n = 0
// A(m-1, A(m, n-1)) if m > 0 and n > 0
//
// Using mfn (memoized function) makes this practical for larger inputs
// by caching computed values.
mfn ackermann(m int, n int) {
// Base case: m = 0 -> return n + 1
m > eq?(0) > is_base
is_base > (cond bool) {
cond > eq?(false) > return?()
n > add(1) > result
return(result)
}(int) > base_result
base_result > present?() > return?(base_result)
// Case: n = 0 -> return A(m-1, 1)
n > eq?(0) > is_n_zero
is_n_zero > (cond bool) {
cond > eq?(false) > return?()
m > sub(1) > m_minus_1
m_minus_1 > ackermann(1) > result
return(result)
}(int) > zero_result
zero_result > present?() > return?(zero_result)
// Recursive case: m > 0 and n > 0
// A(m-1, A(m, n-1))
m > sub(1) > m_minus_1
n > sub(1) > n_minus_1
m > ackermann(n_minus_1) > inner
m_minus_1 > ackermann(inner) > result
return(result)
}(int)
fn print_ackermann(m int, n int) {
m > ackermann(n) > result
println("A({0}, {1}) = {2}", m, n, result)
}()
// Test small values (larger values grow extremely fast)
println("Ackermann function values (memoized):")
println()
// A(0, n) = n + 1
0 > print_ackermann(0)
0 > print_ackermann(1)
0 > print_ackermann(2)
0 > print_ackermann(3)
0 > print_ackermann(4)
println()
// A(1, n) = n + 2
1 > print_ackermann(0)
1 > print_ackermann(1)
1 > print_ackermann(2)
1 > print_ackermann(3)
1 > print_ackermann(4)
println()
// A(2, n) = 2n + 3
2 > print_ackermann(0)
2 > print_ackermann(1)
2 > print_ackermann(2)
2 > print_ackermann(3)
2 > print_ackermann(4)
println()
// A(3, n) = 2^(n+3) - 3
3 > print_ackermann(0)
3 > print_ackermann(1)
3 > print_ackermann(2)
3 > print_ackermann(3)
3 > print_ackermann(4)
println()
// With memoization, we can compute larger values!
// A(3, 10) = 8189
// A(3, 12) = 32765
3 > print_ackermann(10)
3 > print_ackermann(12)
println()
// A(4, 0) = 13
// A(4, 1) = 65533 - now computable with memoization!
4 > print_ackermann(0)
4 > print_ackermann(1)