Code Comparison
See how 26 languages express the same programming concepts.
Click tabs to switch features.
← Back to Beauty Index Read the methodology → Score justifications →
Variable Declaration
Basic variable syntax, type annotations, and initialization patterns.
name = "Python"count: int = 0languages: list[str] = ["Python", "Ruby"]
x, y = 10, 20count += 1
PI: float = 3.14159name = "Ruby"count = 0languages = ["Ruby", "Python"]
x, y = 10, 20count += 1
MAX_SIZE = 1024@instance_var = "hello"name = "Elixir"age = 12{status, message} = {:ok, "Connected"}
[head | tail] = [1, 2, 3, 4]%{name: lang} = %{name: "Elixir", year: 2011}let name = "Rust";let mut count: i32 = 0;let (x, y) = (10, 20);
count += 1;
const MAX_SIZE: usize = 1024;let inferred = vec![1, 2, 3];greeting :: Stringgreeting = "Hello, World!"
add :: Int -> Int -> Intadd x y = x + y
result :: Intresult = add 3 7(def name "Clojure")(def languages ["Clojure" "Java"])
(let [count 0 x 10 y 20 total (+ x y)] (println name total))let name = "F#"let mutable count = 0let languages = ["F#"; "C#"; "OCaml"]
count <- count + 1
let x, y = 10, 20let pi : float = 3.14159let name = "Gleam"let count: Int = 0let languages = ["Gleam", "Erlang"]
let #(x, y) = #(10, 20)
let result = count + x + yval name = "Kotlin"var count: Int = 0val languages = listOf("Kotlin", "Java", "Scala")
count += 1
val (x, y) = Pair(10, 20)val nullable: String? = nulllet name = "Swift"var count: Int = 0let languages = ["Swift", "Objective-C"]
count += 1
let optional: String? = nillet (x, y) = (10, 20)(defvar *name* "Lisp")(defparameter *count* 0)
(let ((x 10) (y 20) (langs '("Lisp" "Scheme"))) (+ x y (length langs)))let name = "OCaml"let count = ref 0let languages = ["OCaml"; "Haskell"]
let () = count := !count + 1
let x, y = 10, 20let (pi : float) = 3.14159name := "Go"var count int = 0languages := []string{"Go", "C"}
count++
var ( x = 10 y = 20)const MaxSize = 1024name = "Julia"count::Int = 0languages = ["Julia", "Python"]
count += 1
x, y = 10, 20const MAX_SIZE = 1024val name = "Scala"var count: Int = 0val languages = List("Scala", "Java")
count += 1
val (x, y) = (10, 20)lazy val expensive = computeResult()const name = "Zig";var count: i32 = 0;const languages = [_][]const u8{ "Zig", "C" };
count += 1;
const x: u32 = 10;const y: u32 = 20;const name: string = "TypeScript";let count = 0;const languages: string[] = ["TS", "JS"];
count += 1;
const [x, y] = [10, 20];const { age, ...rest } = { age: 30, name: "TS" };char *name = "C";int count = 0;const char *languages[] = {"C", "C++"};
count++;
int x = 10, y = 20;#define MAX_SIZE 1024local name = "Lua"local count = 0local languages = {"Lua", "C"}
count = count + 1
local x, y = 10, 20-- No constants in Luafinal name = 'Dart';var count = 0;final languages = <String>['Dart', 'Flutter'];
count++;
const maxSize = 1024;String? nullable;late final String deferred;var name = "C#";int count = 0;var languages = new List<string> { "C#", "F#" };
count++;
var (x, y) = (10, 20);const int MaxSize = 1024;name <- "R"count <- 0Llanguages <- c("R", "Python")
count <- count + 1L
x <- 10; y <- 20MAX_SIZE <- 1024LString name = "Java";int count = 0;var languages = List.of("Java", "Kotlin");
count++;
final int MAX_SIZE = 1024;var x = 10;var y = 20;const name = "JavaScript";let count = 0;const languages = ["JS", "TS"];
count++;
const [x, y] = [10, 20];const { age, ...rest } = { age: 30, name: "JS" };auto name = std::string("C++");int count = 0;auto languages = std::vector<std::string>{"C++", "C"};
count++;
auto [x, y] = std::pair(10, 20);constexpr int MAX_SIZE = 1024;$name = 'PHP';$count = 0;$languages = ['PHP', 'Python'];
$count++;
[$x, $y] = [10, 20];define('MAX_SIZE', 1024);const VERSION = '8.3';If/Else
Conditional branching and control flow expressions.
if score >= 90: label = "excellent"elif score >= 70: label = "good"elif score >= 50: label = "average"else: label = "needs improvement"label = if score >= 90 "excellent" elsif score >= 70 "good" elsif score >= 50 "average" else "needs improvement" endcond do score >= 90 -> "excellent" score >= 70 -> "good" score >= 50 -> "average" true -> "needs improvement"endlet label = if score >= 90 { "excellent"} else if score >= 70 { "good"} else if score >= 50 { "average"} else { "needs improvement"};classify :: Int -> Stringclassify n | n < 0 = "negative" | n == 0 = "zero" | n < 100 = "small" | otherwise = "large"(cond (>= score 90) "excellent" (>= score 70) "good" (>= score 50) "average" :else "needs improvement")let label = if score >= 90 then "excellent" elif score >= 70 then "good" elif score >= 50 then "average" else "needs improvement"let label = case score { s if s >= 90 -> "excellent" s if s >= 70 -> "good" s if s >= 50 -> "average" _ -> "needs improvement"}val label = when { score >= 90 -> "excellent" score >= 70 -> "good" score >= 50 -> "average" else -> "needs improvement"}var label: Stringif score >= 90 { label = "excellent"} else if score >= 70 { label = "good"} else if score >= 50 { label = "average"} else { label = "needs improvement"}(cond ((>= score 90) "excellent") ((>= score 70) "good") ((>= score 50) "average") (t "needs improvement"))let label = if score >= 90 then "excellent" else if score >= 70 then "good" else if score >= 50 then "average" else "needs improvement"var label stringif score >= 90 { label = "excellent"} else if score >= 70 { label = "good"} else if score >= 50 { label = "average"} else { label = "needs improvement"}label = if score >= 90 "excellent"elseif score >= 70 "good"elseif score >= 50 "average"else "needs improvement"endval label = if score >= 90 then "excellent" else if score >= 70 then "good" else if score >= 50 then "average" else "needs improvement"const label = if (score >= 90) "excellent"else if (score >= 70) "good"else if (score >= 50) "average"else "needs improvement";function describe(value: string | number): string { if (typeof value === "number") { return value > 0 ? "positive" : "non-positive"; } else { return value.length > 0 ? "non-empty" : "empty"; }}const char *label;if (score >= 90) { label = "excellent";} else if (score >= 70) { label = "good";} else if (score >= 50) { label = "average";} else { label = "needs improvement";}local labelif score >= 90 then label = "excellent"elseif score >= 70 then label = "good"elseif score >= 50 then label = "average"else label = "needs improvement"endString classify(int? score) { if (score == null) return 'unknown'; if (score >= 90) return 'excellent'; if (score >= 70) return 'good'; if (score >= 50) return 'average'; return 'needs improvement';}var label = score switch{ >= 90 => "excellent", >= 70 => "good", >= 50 => "average", _ => "needs improvement"};label <- if (score >= 90) { "excellent"} else if (score >= 70) { "good"} else if (score >= 50) { "average"} else { "needs improvement"}String label;if (score >= 90) { label = "excellent";} else if (score >= 70) { label = "good";} else if (score >= 50) { label = "average";} else { label = "needs improvement";}const label = score >= 90 ? "excellent" : score >= 70 ? "good" : score >= 50 ? "average" : "needs improvement";std::string classify(int score) { if (score >= 90) return "excellent"; else if (score >= 70) return "good"; else if (score >= 50) return "average"; else return "needs improvement";}$label = match(true) { $score >= 90 => 'excellent', $score >= 70 => 'good', $score >= 50 => 'average', default => 'needs improvement',};Loops
For/while iteration patterns and loop constructs.
for i in range(10): print(i)
for index, value in enumerate(items): print(f"{index}: {value}")
total = 0while total < 100: total += 1010.times { |i| puts i }
items.each_with_index do |item, i| puts "#{i}: #{item}"end
total = 0total += 10 while total < 100Enum.each(1..10, fn i -> IO.puts(i)end)
for x <- 1..10, rem(x, 2) == 0, do: x * x
def sum_to(0), do: 0def sum_to(n), do: n + sum_to(n - 1)for i in 0..10 { println!("{}", i);}
let mut sum = 0;let mut n = 1;while n <= 100 { sum += n; n += 1;}-- Haskell uses recursion, not loopsfactorial :: Integer -> Integerfactorial 0 = 1factorial n = n * factorial (n - 1)
evens :: [Int] -> [Int]evens xs = [x | x <- xs, even x](doseq [i (range 10)] (println i))
(loop [sum 0 n 1] (if (> n 100) sum (recur (+ sum n) (inc n))))for i in 1 .. 10 do printfn "%d" i
for (index, value) in List.indexed items do printfn "%d: %A" index value
let mutable total = 0while total < 100 do total <- total + 10import gleam/listimport gleam/io
pub fn print_items(items: List(String)) { list.each(items, fn(item) { io.println(item) })}
pub fn sum(items: List(Int)) -> Int { list.fold(items, 0, fn(acc, n) { acc + n })}for (i in 1..10) { println(i)}
for ((index, value) in list.withIndex()) { println("$index: $value")}
var sum = 0while (sum < 100) { sum += 10 }for i in 1...10 { print(i)}
for (index, value) in list.enumerated() { print("\(index): \(value)")}
for i in stride(from: 0, to: 100, by: 5) { print(i)}(loop for i from 1 to 10 do (print i))
(loop for x in '(1 2 3 4 5) when (evenp x) sum x into total finally (return total))for i = 0 to 9 do Printf.printf "%d\n" idone
let rec sum_to n = if n <= 0 then 0 else n + sum_to (n - 1)for i := 0; i < 10; i++ { fmt.Println(i)}
for index, value := range items { fmt.Printf("%d: %s\n", index, value)}
sum := 0for sum < 100 { sum += 10}for i in 1:10 println(i)end
for (i, val) in enumerate(items) println("$i: $val")end
total = 0while total < 100 total += 10endfor i <- 1 to 10 do println(i)
for (index, value) <- list.zipWithIndexdo println(s"$index: $value")
var sum = 0while sum < 100 do sum += 10for (items, 0..) |item, index| { std.debug.print("{}: {s}\n", .{ index, item });}
var sum: u32 = 0;var i: u32 = 0;while (i < 10) : (i += 1) { sum += i;}for (const item of items) { console.log(item);}
items.forEach((item, index) => { console.log(`${index}: ${item}`);});
for (let i = 0; i < 10; i++) { console.log(i);}for (int i = 0; i < 10; i++) { printf("%d\n", i);}
int sum = 0;while (sum < 100) { sum += 10;}
do { process();} while (has_more());for i = 1, 10 do print(i)end
for index, value in ipairs(items) do print(index .. ": " .. value)end
local total = 0while total < 100 do total = total + 10endfor (final item in items) { print(item);}
for (var i = 0; i < 10; i++) { print(i);}
var sum = 0;while (sum < 100) { sum += 10; }foreach (var item in items){ Console.WriteLine(item);}
for (var i = 0; i < 10; i++){ Console.WriteLine(i);}
var sum = 0;while (sum < 100) sum += 10;for (i in 1:10) { print(i)}
for (item in items) { print(item)}
total <- 0while (total < 100) { total <- total + 10}for (var item : items) { System.out.println(item);}
for (int i = 0; i < 10; i++) { System.out.println(i);}
int sum = 0;while (sum < 100) { sum += 10; }for (const item of items) { console.log(item);}
items.forEach((item, index) => { console.log(`${index}: ${item}`);});
for (let i = 0; i < 10; i++) { console.log(i);}for (const auto& item : items) { std::cout << item << "\n";}
for (int i = 0; i < 10; ++i) { std::cout << i << "\n";}
auto sum = 0;while (sum < 100) { sum += 10; }foreach ($items as $index => $item) { echo "$index: $item\n";}
for ($i = 0; $i < 10; $i++) { echo "$i\n";}
$sum = 0;while ($sum < 100) { $sum += 10; }Functions
Function definition, parameters, return types, and closures.
def greet(name: str) -> str: return f"Hello, {name}!"
def apply(f, x): return f(x)
double = lambda x: x * 2
def make_adder(n): return lambda x: x + ndef greet(name) "Hello, #{name}!"end
def apply(value, &block) block.call(value)end
double = ->(x) { x * 2 }triple = proc { |x| x * 3 }def greet(name) do "Hello, #{name}!"end
def validate(input) when is_binary(input) do {:ok, input}end
square = fn x -> x * x endapply = &(&1 + &2)fn greet(name: &str) -> String { format!("Hello, {}!", name)}
fn apply<F, T, R>(f: F, x: T) -> Rwhere F: Fn(T) -> R { f(x)}
let double = |x: i32| x * 2;greet :: String -> Stringgreet name = "Hello, " ++ name ++ "!"
apply :: (a -> b) -> a -> bapply f x = f x
compose :: (b -> c) -> (a -> b) -> a -> ccompose f g x = f (g x)(defn greet [name] (str "Hello, " name "!"))
(defn apply-fn [f x] (f x))
(def double #(* % 2))(def add (fn [a b] (+ a b)))let greet name = sprintf "Hello, %s!" name
let apply f x = f x
let double = fun x -> x * 2let add a b = a + blet composed = greet >> String.lengthimport gleam/string
pub fn greet(name: String) -> String { string.concat(["Hello, ", name, "!"])}
pub fn apply(f: fn(a) -> b, x: a) -> b { f(x)}
pub fn double(x: Int) -> Int { x * 2}fun greet(name: String): String = "Hello, $name!"
fun <T, R> apply(value: T, f: (T) -> R): R = f(value)
val double = { x: Int -> x * 2 }val sum = listOf(1, 2, 3).fold(0) { acc, n -> acc + n }func greet(_ name: String) -> String { "Hello, \(name)!"}
func apply<T, R>(_ f: (T) -> R, to value: T) -> R { f(value)}
let double = { (x: Int) in x * 2 }(defun greet (name) (format nil "Hello, ~a!" name))
(defun apply-fn (f x) (funcall f x))
(let ((double (lambda (x) (* x 2)))) (apply-fn double 21))let greet name = Printf.sprintf "Hello, %s!" name
let apply f x = f x
let double = fun x -> x * 2let add a b = a + blet composed = Fun.compose String.length greetfunc greet(name string) string { return fmt.Sprintf("Hello, %s!", name)}
func apply(f func(int) int, x int) int { return f(x)}
double := func(x int) int { return x * 2 }function greet(name::String)::String "Hello, $name!"end
greet(name) = "Hello, $name!"
double = x -> x * 2apply(f, x) = f(x)def greet(name: String): String = s"Hello, $name!"
def apply[T, R](f: T => R)(x: T): R = f(x)
val double = (x: Int) => x * 2val add: (Int, Int) => Int = _ + _fn greet(name: []const u8) void { std.debug.print("Hello, {s}!\n", .{name});}
fn apply(comptime T: type, f: fn (T) T, x: T) T { return f(x);}function greet(name: string): string { return `Hello, ${name}!`;}
const apply = <T, R>(f: (x: T) => R, x: T): R => f(x);
const double = (x: number) => x * 2;const pipe = <T>(...fns: ((x: T) => T)[]) => (x: T) => fns.reduce((v, f) => f(v), x);char* greet(const char *name) { static char buf[64]; snprintf(buf, sizeof(buf), "Hello, %s!", name); return buf;}
int apply(int (*f)(int), int x) { return f(x);}function greet(name) return "Hello, " .. name .. "!"end
local apply = function(f, x) return f(x)end
local double = function(x) return x * 2 endString greet(String name) => 'Hello, $name!';
T apply<T>(T Function(T) f, T x) => f(x);
final doubler = (int x) => x * 2;
void forEach<T>(List<T> items, void Function(T) action) { for (final item in items) action(item);}string Greet(string name) => $"Hello, {name}!";
T Apply<T>(Func<T, T> f, T x) => f(x);
Func<int, int> doubler = x => x * 2;var sum = numbers.Aggregate(0, (acc, n) => acc + n);greet <- function(name) { paste0("Hello, ", name, "!")}
apply_fn <- function(f, x) f(x)
double <- function(x) x * 2
make_adder <- function(n) { function(x) x + n}String greet(String name) { return "Hello, " + name + "!";}
<T, R> R apply(Function<T, R> f, T x) { return f.apply(x);}
Function<Integer, Integer> doubler = x -> x * 2;function greet(name) { return `Hello, ${name}!`;}
const apply = (f, x) => f(x);
const double = x => x * 2;const makeAdder = n => x => x + n;std::string greet(std::string_view name) { return std::format("Hello, {}!", name);}
template<typename F, typename T>auto apply(F f, T x) { return f(x); }
auto doubler = [](int x) { return x * 2; };function greet(string $name): string { return "Hello, $name!";}
$apply = fn($f, $x) => $f($x);$double = fn($x) => $x * 2;
$makeAdder = fn($n) => fn($x) => $x + $n;Structs
Data structure definition using classes, structs, records, or equivalent.
from dataclasses import dataclass
@dataclassclass User: name: str email: str age: int = 0
def greeting(self) -> str: return f"Hello, {self.name}!"User = Struct.new(:name, :email, :age) do def greeting "Hello, #{name}!" endend
user = User.new("Alice", "alice@ex.com", 30)puts user.greetingdefmodule User do defstruct [:name, :email, age: 0]
def new(name, email, age) do %User{name: name, email: email, age: age} end
def greeting(%User{name: name}) do "Hello, #{name}!" endend#[derive(Debug, Clone)]struct User { name: String, email: String, age: u32,}
impl User { fn new(name: &str, email: &str, age: u32) -> Self { Self { name: name.into(), email: email.into(), age } }}data User = User { userName :: String , userEmail :: String , userAge :: Int } deriving (Show, Eq)
data Shape = Circle Double | Rectangle Double Double(defrecord User [name email age])
(defprotocol Greetable (greeting [this]))
(extend-type User Greetable (greeting [this] (str "Hello, " (:name this) "!")))
(def user (->User "Alice" "alice@ex.com" 30))type User = { Name: string Email: string Age: int } member this.Greeting = sprintf "Hello, %s!" this.Name
let user = { Name = "Alice"; Email = "a@b.c"; Age = 30 }let updated = { user with Age = 31 }import gleam/string
pub type User { User(name: String, email: String, age: Int)}
pub fn greeting(user: User) -> String { string.concat(["Hello, ", user.name, "!"])}
pub fn new_user(name: String, email: String) -> User { User(name: name, email: email, age: 0)}data class User( val name: String, val email: String, val age: Int) { fun greeting(): String = "Hello, $name!"}
val user = User("Alice", "alice@ex.com", 30)val updated = user.copy(age = 31)struct User: Codable, Equatable { let name: String let email: String var age: Int
func greeting() -> String { "Hello, \(name)!" }}
let user = User(name: "Alice", email: "a@b.c", age: 30)(defclass user () ((name :initarg :name :accessor user-name) (age :initarg :age :accessor user-age)))
(defgeneric greet (obj))(defmethod greet ((u user)) (format nil "Hello, ~a!" (user-name u)))
(greet (make-instance 'user :name "Alice" :age 30))type user = { name : string; email : string; age : int;}
let greeting u = Printf.sprintf "Hello, %s!" u.name
let user = { name = "Alice"; email = "a@b.c"; age = 30 }let updated = { user with age = 31 }type User struct { Name string Email string Age int}
func NewUser(name, email string, age int) User { return User{Name: name, Email: email, Age: age}}
func (u User) Greeting() string { return fmt.Sprintf("Hello, %s!", u.Name)}struct User name::String email::String age::Intend
greeting(u::User) = "Hello, $(u.name)!"
mutable struct MutableUser name::String age::Intendcase class User( name: String, email: String, age: Int = 0): def greeting: String = s"Hello, $name!"
val user = User("Alice", "alice@ex.com", 30)val updated = user.copy(age = 31)const User = struct { name: []const u8, email: []const u8, age: u32,
pub fn greeting(self: User) void { std.debug.print("Hello, {s}!\n", .{self.name}); }};
const user = User{ .name = "Alice", .email = "a@b.c", .age = 30 };interface User { readonly name: string; readonly email: string; age: number;}
class UserImpl implements User { constructor( public readonly name: string, public readonly email: string, public age: number ) {}
greeting(): string { return `Hello, ${this.name}!`; }}typedef struct { char name[64]; char email[128]; int age;} User;
void user_greeting(const User *u) { printf("Hello, %s!\n", u->name);}
User user = { .name = "Alice", .email = "a@b.c", .age = 30 };local User = {}User.__index = User
function User.new(name, email, age) return setmetatable({ name = name, email = email, age = age }, User)end
function User:greeting() return "Hello, " .. self.name .. "!"endclass User { final String name; final String email; final int age;
const User({ required this.name, required this.email, this.age = 0, });
String greeting() => 'Hello, $name!';}public record User( string Name, string Email, int Age = 0) { public string Greeting() => $"Hello, {Name}!";}
var user = new User("Alice", "alice@ex.com", 30);var updated = user with { Age = 31 };new_user <- function(name, email, age = 0L) { structure( list(name = name, email = email, age = age), class = "User" )}
greeting <- function(user, ...) UseMethod("greeting")
greeting.User <- function(user, ...) { paste0("Hello, ", user$name, "!")}public record User( String name, String email, int age) { public String greeting() { return "Hello, " + name + "!"; }}
var user = new User("Alice", "alice@ex.com", 30);class User { constructor(name, email, age = 0) { this.name = name; this.email = email; this.age = age; }
greeting() { return `Hello, ${this.name}!`; }}struct User { std::string name; std::string email; int age;
User(std::string n, std::string e, int a) : name(std::move(n)), email(std::move(e)), age(a) {}
std::string greeting() const { return std::format("Hello, {}!", name); }};readonly class User { public function __construct( public string $name, public string $email, public int $age = 0, ) {}
public function greeting(): string { return "Hello, {$this->name}!"; }}Pattern Matching
Native pattern matching constructs for destructuring and control flow.
match command: case ["quit"]: quit() case ["go", direction]: move(direction) case ["get", item] if item in inventory: pick_up(item) case _: print("Unknown command")case datain { name: String => name, age: (18..) => age } puts "Adult: #{name}, #{age}"in { name: String => name, age: Integer => age } puts "Minor: #{name}, #{age}"in [Integer => x, Integer => y] puts "Point: #{x}, #{y}"endcase list do [] -> "empty" [x] -> "just #{x}" [h | _] when h > 0 -> "starts positive" _ -> "other"end
# Function clause pattern matching (inside a module)# def handle({:ok, result}), do: result# def handle({:error, reason}), do: raise reason
{:ok, value} = {:ok, 42}fn describe(value: &Option<Vec<i32>>) -> &str { match value { None => "nothing", Some(v) if v.is_empty() => "empty list", Some(v) if v.len() == 1 => "singleton", Some(v) => "list", }}describe :: (Show a, Num a, Ord a) => [a] -> Stringdescribe xs = case xs of [] -> "empty" [x] -> "singleton: " ++ show x [x,y] -> "pair: " ++ show x ++ "," ++ show y (x:_) | x > 0 -> "starts positive" | otherwise -> "starts non-positive"(require '[clojure.core.match :refer [match]])
(match [x y] [_ 0] "y is zero" [0 _] "x is zero" [a b] (str "both non-zero: " a ", " b))
(let [{:keys [name age]} person] (str name " is " age))let describe = function | [] -> "empty" | [x] -> sprintf "singleton: %A" x | x :: _ when x > 0 -> "starts positive" | _ -> "other"
let area = function | Circle r -> System.Math.PI * r * r | Rect (w, h) -> w * hpub fn describe(items: List(Int)) -> String { case items { [] -> "empty" [x] -> "singleton" [x, ..] if x > 0 -> "starts positive" _ -> "other" }}
pub fn unwrap(result: Result(a, b), default: a) -> a { case result { Ok(value) -> value Error(_) -> default }}fun describe(shape: Shape): String = when (shape) { is Circle -> "circle r=${shape.radius}" is Rectangle -> "rect ${shape.w}x${shape.h}" is Triangle -> "triangle"}
val (name, age) = personwhen { age < 18 -> "minor" else -> "adult"}func describe(_ value: Any) -> String { switch value { case let n as Int where n > 0: return "positive int: \(n)" case let s as String: return "string: \(s)" case let (x, y) as (Int, Int): return "pair: \(x), \(y)" default: return "unknown" }}(defun describe-val (x) (typecase x (integer (format nil "int: ~d" x)) (string (format nil "str: ~a" x)) (list (format nil "~d items" (length x))) (t "unknown")))
(describe-val 42)(describe-val '(1 2 3))let describe = function | [] -> "empty" | [x] -> Printf.sprintf "singleton: %d" x | x :: _ when x > 0 -> "starts positive" | _ -> "other"
let area = function | Circle r -> Float.pi *. r *. r | Rect (w, h) -> w *. hdescribe(::Nothing) = "nothing"describe(x::Int) = x > 0 ? "positive" : "non-positive"describe(s::String) = "string: $s"describe(v::Vector) = isempty(v) ? "empty" : "list"describe(_) = "unknown"def describe(x: Any): String = x match case i: Int if i > 0 => s"positive: $i" case s: String => s"string: $s" case (a, b) => s"pair: $a, $b" case head :: _ => s"list starting with $head" case _ => "unknown"type Shape = | { kind: "circle"; radius: number } | { kind: "rect"; w: number; h: number };
function area(shape: Shape): number { switch (shape.kind) { case "circle": return Math.PI * shape.radius ** 2; case "rect": return shape.w * shape.h; }}String describe(Object obj) => switch (obj) { int n when n > 0 => 'positive: $n', String s => 'string: $s', (int x, int y) => 'point: $x, $y', _ => 'unknown',};string Describe(object obj) => obj switch{ int n when n > 0 => $"positive: {n}", string s => $"string: {s}", (int x, int y) => $"point: {x},{y}", null => "null", _ => "unknown"};Error Handling
Exception handling via try/catch or Result/Either patterns.
def parse_number(s: str) -> int: try: return int(s) except ValueError as e: raise ValueError(f"Invalid: {s}") from e
try: result = parse_number(input_str)except ValueError: result = -1finally: cleanup()def parse_number(str) Integer(str)rescue ArgumentError => e raise "Invalid input: #{str}"end
begin result = parse_number(input)rescue => e puts "Error: #{e.message}" result = -1ensure cleanupendwith {:ok, user} <- fetch_user(id), {:ok, posts} <- fetch_posts(user.id), {:ok, _} <- validate(posts) do {:ok, format_response(user, posts)}else {:error, :not_found} -> {:error, "User not found"} {:error, reason} -> {:error, reason}enduse std::num::ParseIntError;
fn parse_and_double(s: &str) -> Result<i32, ParseIntError> { let n = s.parse::<i32>()?; Ok(n * 2)}
fn main() { match parse_and_double("42") { Ok(val) => println!("Got: {}", val), Err(e) => eprintln!("Error: {}", e), }}type Error = String
safeDivide :: Double -> Double -> Either Error DoublesafeDivide _ 0 = Left "Division by zero"safeDivide a b = Right (a / b)
compute :: Either Error Doublecompute = do x <- safeDivide 10 2 y <- safeDivide x 3 return (x + y)(defn parse-number [s] (try (Integer/parseInt s) (catch NumberFormatException _ (throw (ex-info "Invalid input" {:input s})))))
(try (parse-number "42") (catch Exception e (println "Error:" (ex-message e))))let safeDivide a b = if b = 0.0 then Error "Division by zero" else Ok (a / b)
let compute = safeDivide 10.0 2.0 |> Result.bind (fun x -> safeDivide x 3.0) |> Result.map (fun y -> y + 1.0)
match compute with| Ok v -> printfn "Got: %f" v| Error e -> printfn "Error: %s" eimport gleam/intimport gleam/result
pub fn parse_number(s: String) -> Result(Int, String) { int.parse(s) |> result.replace_error("Invalid: " <> s)}
pub fn compute(input: String) -> Result(Int, String) { use n <- result.try(parse_number(input)) Ok(n * 2)}fun parseNumber(s: String): Result<Int> = runCatching { s.toInt() }
val result = parseNumber("42") .map { it * 2 } .getOrElse { -1 }
val value = try { riskyOperation()} catch (e: IOException) { fallbackValue}enum ParseError: Error { case invalidInput(String)}
func parse(_ s: String) throws -> Int { guard let n = Int(s) else { throw ParseError.invalidInput(s) } return n}
let result = try? parse("42") ?? -1(define-condition bad-input (error) ((val :initarg :val :reader bad-val)))
(defun parse (s) (restart-case (error 'bad-input :val s) (use-value (v) v)))
(handler-bind ((bad-input (lambda (c) (invoke-restart 'use-value 0)))) (parse "x"))let safe_divide a b = if b = 0.0 then Error "Division by zero" else Ok (a /. b)
let compute = Result.bind (safe_divide 10.0 2.0) (fun x -> safe_divide x 3.0)
match compute with| Ok v -> Printf.printf "Got: %f\n" v| Error e -> Printf.printf "Error: %s\n" efunc parseNumber(s string) (int, error) { n, err := strconv.Atoi(s) if err != nil { return 0, fmt.Errorf("invalid input %q: %w", s, err) } return n, nil}
if result, err := parseNumber("42"); err != nil { log.Fatal(err)} else { fmt.Println(result)}function parse_number(s::String) try parse(Int, s) catch e if isa(e, ArgumentError) error("Invalid input: $s") end rethrow() endend
result = try parse_number("42")catch e -1endimport scala.util.{Try, Success, Failure}
def parse(s: String): Either[String, Int] = Try(s.toInt).toEither.left.map(_.getMessage)
val result = for x <- parse("42") y <- parse("7")yield x + y
result match case Right(v) => println(s"Got: $v") case Left(e) => println(s"Error: $e")const ParseError = error{InvalidInput};
fn parseNumber(s: []const u8) ParseError!i32 { return std.fmt.parseInt(i32, s, 10) catch { return error.InvalidInput; };}
const result = parseNumber("42") catch |err| { std.debug.print("Error: {}\n", .{err}); return;};type Result<T> = { ok: true; value: T } | { ok: false; error: Error };
function safeParse(s: string): Result<number> { const n = Number(s); return isNaN(n) ? { ok: false, error: new Error(`Invalid: ${s}`) } : { ok: true, value: n };}
const result = safeParse("42");if (result.ok) console.log(result.value);#include <errno.h>
int parse_number(const char *s, int *out) { char *end; errno = 0; long val = strtol(s, &end, 10); if (errno != 0 || *end != '\0') return -1; *out = (int)val; return 0;}
int result;if (parse_number("42", &result) != 0) fprintf(stderr, "Invalid input\n");local ok, result = pcall(function() return tonumber("42") or error("invalid")end)
if ok then print("Got: " .. result)else print("Error: " .. result)end
local ok2, val = xpcall(risky_fn, debug.traceback)int parseNumber(String s) { try { return int.parse(s); } on FormatException catch (e) { throw ArgumentError('Invalid: $s'); }}
try { final result = parseNumber('42'); print(result);} catch (e) { print('Error: $e');}try{ var result = int.Parse(input); Console.WriteLine(result * 2);}catch (FormatException e) when (e.Message.Contains("Input")){ Console.WriteLine($"Invalid: {e.Message}");}catch (Exception e){ Console.WriteLine($"Error: {e.Message}");}finally { Cleanup(); }parse_number <- function(s) { tryCatch( as.integer(s), warning = function(w) stop(paste("Invalid:", s)) )}
result <- tryCatch( parse_number("42"), error = function(e) { message("Error: ", conditionMessage(e)) -1L })int parseNumber(String s) throws NumberFormatException { return Integer.parseInt(s);}
try { var result = parseNumber("42"); System.out.println(result);} catch (NumberFormatException e) { System.err.println("Invalid: " + e.getMessage());} finally { cleanup();}async function fetchData(url) { try { const response = await fetch(url); if (!response.ok) throw new Error(`HTTP ${response.status}`); return await response.json(); } catch (error) { console.error("Fetch failed:", error.message); return null; }}#include <stdexcept>
int parseNumber(const std::string& s) { try { return std::stoi(s); } catch (const std::invalid_argument& e) { throw std::runtime_error("Invalid: " + s); }}
try { auto result = parseNumber("42");} catch (const std::exception& e) { std::cerr << e.what() << "\n";}function parseNumber(string $s): int { if (!is_numeric($s)) { throw new InvalidArgumentException("Invalid: $s"); } return (int) $s;}
try { $result = parseNumber('42');} catch (InvalidArgumentException $e) { echo "Error: " . $e->getMessage();} finally { cleanup();}String Interpolation
Embedding expressions and variables within string literals.
name = "Python"version = 3.12
msg = f"Hello, {name}! Version: {version}"expr = f"Length: {len(name)}, Upper: {name.upper()}"aligned = f"{name:<10} | {version:>5.1f}"debug = f"{name!r} has {len(name)} chars"name = "Ruby"version = 3.3
msg = "Hello, #{name}! Version: #{version}"expr = "Length: #{name.length}, Upper: #{name.upcase}"heredoc = <<~TEXT Welcome to #{name}. Version: #{version}TEXTname = "Elixir"version = 1.16
msg = "Hello, #{name}! Version: #{version}"multi = """Welcome to #{String.upcase(name)}.Released: #{version}"""let name = "Rust";let version = 2024;
let msg = format!("Hello, {}! Version: {}", name, version);let aligned = format!("{:<10} | {:>5}", name, version);let debug = format!("Value: {:?}", some_struct);
println!("Welcome to {name} {version}!");import Text.Printf (printf)
-- Haskell uses concatenation or printfgreeting :: String -> Int -> Stringgreeting name age = "Hello, " ++ name ++ "! You are " ++ show age ++ " years old."
msg :: Stringmsg = printf "Hello, %s! Age: %d" name age(def name "Clojure")(def version 1.12)
(str "Hello, " name "! Version: " version)(format "Hello, %s! Version: %.1f" name version)
(println (str "Welcome to " name ". " "Version: " version))let name = "F#"let version = 8.0
let msg = $"Hello, {name}! Version: {version}"let expr = $"Length: {name.Length}, Upper: {name.ToUpper()}"let formatted = sprintf "%-10s | %5.1f" name versionimport gleam/intimport gleam/string
let name = "Gleam"let version = 1
let msg = "Hello, " <> name <> "! Version: " <> int.to_string(version)
let multi = string.concat([ "Welcome to ", name, ".\n", "Version: ", int.to_string(version),])val name = "Kotlin"val version = 2.0
val msg = "Hello, $name! Version: $version"val expr = "Length: ${name.length}, Upper: ${name.uppercase()}"val multi = """ |Welcome to $name |Version: $version""".trimMargin()let name = "Swift"let version = 5.10
let msg = "Hello, \(name)! Version: \(version)"let expr = "Length: \(name.count), Upper: \(name.uppercased())"let multi = """Welcome to \(name).Version: \(version)"""(defvar *name* "Lisp")(defvar *version* 1994)
(format nil "Hello, ~a!" *name*)(format nil "v~d, caps: ~:@(~a~)" *version* *name*)
(format nil "Items: ~{~a~^, ~}" '("a" "b" "c"))let name = "OCaml"let version = 5.1
let msg = Printf.sprintf "Hello, %s! Version: %.1f" name versionlet () = Printf.printf "Welcome to %s.\nVersion: %.1f\n" name versionname := "Go"version := 1.22
msg := fmt.Sprintf("Hello, %s! Version: %.2f", name, version)aligned := fmt.Sprintf("%-10s | %5.2f", name, version)
fmt.Printf("Welcome to %s.\nVersion: %v\n", name, version)name = "Julia"version = 1.10
msg = "Hello, $name! Version: $version"expr = "Length: $(length(name)), Upper: $(uppercase(name))"
using Printfformatted = @sprintf("%-10s | %5.1f", name, version)val name = "Scala"val version = 3.4
val msg = s"Hello, $name! Version: $version"val expr = s"Length: ${name.length}, Upper: ${name.toUpperCase}"val formatted = f"$name%-10s | $version%5.1f"
val raw = raw"No \n escape: $name"const name = "Zig";const version: f32 = 0.12;
std.debug.print("Hello, {s}! Version: {d:.2}\n", .{ name, version });
var buf: [256]u8 = undefined;const msg = std.fmt.bufPrint(&buf, "Welcome to {s}", .{name}) catch unreachable;const name = "TypeScript";const version = 5.4;
const msg = `Hello, ${name}! Version: ${version}`;const expr = `Length: ${name.length}, Upper: ${name.toUpperCase()}`;const multi = `Welcome to ${name}.Version: ${version}`;const char *name = "C";int version = 23;
printf("Hello, %s! Version: C%d\n", name, version);
char buf[128];snprintf(buf, sizeof(buf), "Welcome to %s. Version: %d", name, version);local name = "Lua"local version = 5.4
local msg = string.format("Hello, %s! Version: %.1f", name, version)local concat = "Hello, " .. name .. "! Version: " .. version
print(string.format("%-10s | %5.1f", name, version))final name = 'Dart';final version = 3.3;
final msg = 'Hello, $name! Version: $version';final expr = 'Length: ${name.length}, Upper: ${name.toUpperCase()}';final multi = '''Welcome to $name.Version: $version''';var name = "C#";var version = 12.0;
var msg = $"Hello, {name}! Version: {version}";var expr = $"Length: {name.Length}, Upper: {name.ToUpper()}";var aligned = $"{name,-10} | {version,5:F1}";var raw = $"""Welcome to {name}. Version: {version}""";name <- "R"version <- 4.3
msg <- paste0("Hello, ", name, "! Version: ", version)expr <- paste("Length:", nchar(name))
formatted <- sprintf("%-10s | %5.1f", name, version)glued <- glue::glue("Welcome to {name}. Version: {version}")String name = "Java";int version = 21;
String msg = "Hello, %s! Version: %d".formatted(name, version);
String multi = """ Welcome to %s. Version: %d """.formatted(name, version);
String concat = "Hello, " + name + "! Version: " + version;const name = "JavaScript";const version = 2024;
const msg = `Hello, ${name}! Version: ${version}`;const expr = `Length: ${name.length}, Upper: ${name.toUpperCase()}`;const multi = `Welcome to ${name}.Version: ${version}`;auto name = std::string("C++");auto version = 23;
auto msg = std::format("Hello, {}! Version: C++{}", name, version);auto aligned = std::format("{:<10} | {:>5}", name, version);
std::println("Welcome to {}. Version: {}", name, version);$name = 'PHP';$version = 8.3;
$msg = "Hello, $name! Version: $version";$expr = "Length: " . strlen($name) . ", Upper: " . strtoupper($name);$heredoc = <<<EOTWelcome to $name.Version: $versionEOT;
$formatted = sprintf("%-10s | %5.1f", $name, $version);List Operations
Map, filter, reduce and functional collection transformations.
numbers = list(range(1, 11))
doubled = [n * 2 for n in numbers]evens = [n for n in numbers if n % 2 == 0]total = sum(numbers)
squares = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, numbers)))numbers = (1..10).to_a
doubled = numbers.map { |n| n * 2 }evens = numbers.select(&:even?)total = numbers.reduce(:+)
result = numbers .select(&:even?) .map { |n| n ** 2 } .sumnumbers = 1..10
doubled = Enum.map(numbers, &(&1 * 2))evens = Enum.filter(numbers, &(rem(&1, 2) == 0))total = Enum.reduce(numbers, 0, &+/2)
result = numbers|> Enum.filter(&(rem(&1, 2) == 0))|> Enum.map(&(&1 * &1))let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let result: Vec<i32> = numbers.iter() .filter(|&&n| n % 2 == 0) .map(|&n| n * n) .collect();
let sum: i32 = numbers.iter().sum();numbers :: [Int]numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
doubled = map (* 2) numbersevens = filter even numberstotal = foldl (+) 0 numberssquares = [x * x | x <- numbers, even x](def numbers (range 1 11))
(def doubled (map #(* % 2) numbers))(def evens (filter even? numbers))(def total (reduce + numbers))
(->> numbers (filter even?) (map #(* % %)) (reduce +))let numbers = [1 .. 10]
let doubled = List.map ((*) 2) numberslet evens = List.filter (fun n -> n % 2 = 0) numberslet total = List.sum numbers
let result = numbers |> List.filter (fun n -> n % 2 = 0) |> List.map (fun n -> n * n) |> List.sumimport gleam/listimport gleam/int
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let doubled = list.map(numbers, fn(n) { n * 2 })let evens = list.filter(numbers, int.is_even)let total = list.fold(numbers, 0, fn(acc, n) { acc + n })
let result = numbers |> list.filter(int.is_even) |> list.map(fn(n) { n * n })val numbers = (1..10).toList()
val doubled = numbers.map { it * 2 }val evens = numbers.filter { it % 2 == 0 }val total = numbers.reduce { acc, n -> acc + n }
val result = numbers .filter { it % 2 == 0 } .map { it * it } .sum()let numbers = Array(1...10)
let doubled = numbers.map { $0 * 2 }let evens = numbers.filter { $0 % 2 == 0 }let total = numbers.reduce(0, +)
let result = numbers .filter { $0.isMultiple(of: 2) } .map { $0 * $0 }(defvar *nums* '(1 2 3 4 5 6 7 8 9 10))
(mapcar (lambda (n) (* n 2)) *nums*)(remove-if-not #'evenp *nums*)(reduce #'+ *nums*)
(reduce #'+ (mapcar (lambda (n) (* n n)) (remove-if-not #'evenp *nums*)))let numbers = List.init 10 (fun i -> i + 1)
let doubled = List.map (( * ) 2) numberslet evens = List.filter (fun n -> n mod 2 = 0) numberslet total = List.fold_left ( + ) 0 numbers
let result = numbers |> List.filter (fun n -> n mod 2 = 0) |> List.map (fun n -> n * n)numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var evens []intfor _, n := range numbers { if n%2 == 0 { evens = append(evens, n) }}
sum := 0for _, n := range numbers { sum += n}numbers = 1:10
doubled = numbers .* 2evens = filter(iseven, collect(numbers))total = sum(numbers)
result = [n^2 for n in numbers if iseven(n)]piped = numbers |> collect |> x -> filter(iseven, x)val numbers = (1 to 10).toList
val doubled = numbers.map(_ * 2)val evens = numbers.filter(_ % 2 == 0)val total = numbers.reduce(_ + _)
val result = numbers .filter(_ % 2 == 0) .map(n => n * n) .sumconst numbers = [_]i32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var sum: i32 = 0;for (numbers) |n| { sum += n;}
var evens: [5]i32 = undefined;var idx: usize = 0;for (numbers) |n| { if (@rem(n, 2) == 0) { evens[idx] = n; idx += 1; }}const numbers = Array.from({ length: 10 }, (_, i) => i + 1);
const doubled = numbers.map(n => n * 2);const evens = numbers.filter(n => n % 2 === 0);const total = numbers.reduce((acc, n) => acc + n, 0);
const result = numbers .filter(n => n % 2 === 0) .map(n => n ** 2);int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int len = sizeof(numbers) / sizeof(numbers[0]);
int sum = 0;for (int i = 0; i < len; i++) sum += numbers[i];
int evens[10], count = 0;for (int i = 0; i < len; i++) if (numbers[i] % 2 == 0) evens[count++] = numbers[i];local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
local evens = {}for _, n in ipairs(numbers) do if n % 2 == 0 then evens[#evens + 1] = n endend
local sum = 0for _, n in ipairs(numbers) do sum = sum + n endfinal numbers = List.generate(10, (i) => i + 1);
final doubled = numbers.map((n) => n * 2).toList();final evens = numbers.where((n) => n % 2 == 0).toList();final total = numbers.reduce((a, b) => a + b);
final result = numbers .where((n) => n % 2 == 0) .map((n) => n * n) .toList();var numbers = Enumerable.Range(1, 10).ToList();
var doubled = numbers.Select(n => n * 2);var evens = numbers.Where(n => n % 2 == 0);var total = numbers.Sum();
var result = numbers .Where(n => n % 2 == 0) .Select(n => n * n) .Sum();numbers <- 1:10
doubled <- numbers * 2evens <- numbers[numbers %% 2 == 0]total <- sum(numbers)
result <- Filter(function(n) n %% 2 == 0, numbers) |> sapply(function(n) n^2)var numbers = IntStream.rangeClosed(1, 10).boxed().toList();
var doubled = numbers.stream().map(n -> n * 2).toList();var evens = numbers.stream().filter(n -> n % 2 == 0).toList();var total = numbers.stream().mapToInt(Integer::intValue).sum();
var result = numbers.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .toList();const numbers = Array.from({ length: 10 }, (_, i) => i + 1);
const doubled = numbers.map(n => n * 2);const evens = numbers.filter(n => n % 2 === 0);const total = numbers.reduce((acc, n) => acc + n, 0);
const result = numbers .filter(n => n % 2 === 0) .map(n => n ** 2);auto numbers = std::views::iota(1, 11) | std::ranges::to<std::vector>();
auto doubled = numbers | std::views::transform([](int n) { return n * 2; });auto evens = numbers | std::views::filter([](int n) { return n % 2 == 0; });auto total = std::accumulate(numbers.begin(), numbers.end(), 0);$numbers = range(1, 10);
$doubled = array_map(fn($n) => $n * 2, $numbers);$evens = array_filter($numbers, fn($n) => $n % 2 === 0);$total = array_sum($numbers);
$result = array_map( fn($n) => $n ** 2, array_filter($numbers, fn($n) => $n % 2 === 0));Signature Idiom
The characteristic code snippet that best represents each language.
from itertools import takewhile
def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b
squares = { n: n**2 for n in takewhile(lambda x: x < 100, fibonacci()) if n > 0}class Array def histogram each_with_object(Hash.new(0)) { |item, counts| counts[item] += 1 } .sort_by { |_, count| -count } .map { |item, count| "#{item}: #{'*' * count}" } .join("\n") endenddef process_order(%Order{items: items, user: user}) do items |> Enum.filter(&(&1.in_stock)) |> Enum.map(&apply_discount(&1, user.tier)) |> Enum.reduce(0, &(&1.price + &2)) |> apply_tax(user.region) |> format_total()endenum Shape { Circle(f64), Rectangle(f64, f64), Triangle(f64, f64, f64),}
fn area(shape: &Shape) -> f64 { match shape { Shape::Circle(r) => std::f64::consts::PI * r * r, Shape::Rectangle(w, h) => w * h, Shape::Triangle(a, b, c) => { let s = (a + b + c) / 2.0; (s * (s - a) * (s - b) * (s - c)).sqrt() } }}quicksort :: Ord a => [a] -> [a]quicksort [] = []quicksort (x:xs) = quicksort smaller ++ [x] ++ quicksort bigger where smaller = [a | a <- xs, a <= x] bigger = [a | a <- xs, a > x](defn process-users [users] (->> users (filter :active) (map :email) (map clojure.string/lower-case) (sort) (dedupe) (into [])))type Shape = | Circle of radius: float | Rect of width: float * height: float
let area = function | Circle r -> System.Math.PI * r * r | Rect (w, h) -> w * h
let totalArea shapes = shapes |> List.map area |> List.sumpub fn main() { "Hello, Joe!" |> string.uppercase |> io.println}data class User(val name: String, val email: String?)
fun greet(users: List<User>): List<String> = users .filter { it.email != null } .sortedBy { it.name } .map { user -> "Hello, ${user.name} (${user.email!!})" }protocol Drawable { func draw() -> String}
extension Drawable { func debugDraw() -> String { "[(draw())]" }}
struct Circle: Drawable { let radius: Double func draw() -> String { "Circle(r=(radius))" }}(defmacro when-let ((var expr) &body body) `(let ((,var ,expr)) (when ,var ,@body)))
(when-let (user (find-user "ada")) (format t "Hello, ~a!" (user-name user)) (log-visit user))type 'a tree = | Leaf | Node of 'a tree * 'a * 'a tree
let rec fold f acc = function | Leaf -> acc | Node (left, value, right) -> let acc = fold f acc left in let acc = f acc value in fold f acc rightfunc fanIn(channels ...<-chan string) <-chan string { merged := make(chan string) var wg sync.WaitGroup for _, ch := range channels { wg.Add(1) go func(c <-chan string) { defer wg.Done() for msg := range c { merged <- msg } }(ch) } go func() { wg.Wait(); close(merged) }() return merged}abstract type Shape endstruct Circle <: Shape; r::Float64 endstruct Rect <: Shape; w::Float64; h::Float64 end
area(c::Circle) = pi * c.r^2area(r::Rect) = r.w * r.h
combine(a::Circle, b::Circle) = Circle(sqrt(a.r^2 + b.r^2))combine(a::Rect, b::Rect) = Rect(a.w + b.w, max(a.h, b.h))combine(a::Shape, b::Shape) = area(a) + area(b)case class User(name: String, age: Int)
def findEligible( users: List[User], minAge: Int): List[String] = for { user <- users if user.age >= minAge initial = user.name.head.toUpper } yield s"$initial. ${user.name} (age ${user.age})"fn fibonacci(comptime n: u32) u128 { var a: u128 = 0; var b: u128 = 1; for (0..n) |_| { const tmp = a; a = b; b = tmp + b; } return a;}
// Computed at compile time, zero runtime costconst fib_50 = fibonacci(50);type Result<T, E = Error> = | { ok: true; value: T } | { ok: false; error: E };
function parse(input: string): Result<number> { const n = Number(input); return isNaN(n) ? { ok: false, error: new Error(`Invalid: ${input}`) } : { ok: true, value: n };}void reverse(char *str) { char *end = str; while (*end) end++; end--;
while (str < end) { char tmp = *str; *str++ = *end; *end-- = tmp; }}local Vector = {}Vector.__index = Vector
function Vector.new(x, y) return setmetatable({x = x, y = y}, Vector)end
function Vector:length() return math.sqrt(self.x^2 + self.y^2)end
function Vector.__add(a, b) return Vector.new(a.x + b.x, a.y + b.y)endfinal paint = Paint() ..color = Colors.blue ..strokeWidth = 4.0 ..style = PaintingStyle.stroke;
final path = Path() ..moveTo(0, 0) ..lineTo(100, 0) ..lineTo(100, 100) ..close();
canvas.drawPath(path, paint);var summary = from order in orders where order.Date.Year == 2024 group order by order.Category into g orderby g.Sum(o => o.Total) descending select new { Category = g.Key, Revenue = g.Sum(o => o.Total), Count = g.Count() };result <- numbers[numbers %% 2 == 0] * 2Map<String, Long> wordFrequency = Files.lines(Path.of("book.txt")) .flatMap(line -> Arrays.stream(line.split("\\s+"))) .map(String::toLowerCase) .filter(w -> w.length() > 3) .collect(Collectors.groupingBy( Function.identity(), Collectors.counting() ));async function fetchUserPosts(userId) { const [user, posts] = await Promise.all([ fetch(`/api/users/${userId}`).then(r => r.json()), fetch(`/api/users/${userId}/posts`).then(r => r.json()), ]);
const { name, avatar } = user; return { name, avatar, posts: posts.slice(0, 5) };}class ResourcePool { std::vector<std::unique_ptr<Connection>> pool_;public: auto acquire() { if (pool_.empty()) pool_.push_back(std::make_unique<Connection>()); auto conn = std::move(pool_.back()); pool_.pop_back(); return std::shared_ptr<Connection>( conn.release(), [this](Connection* c) { pool_.emplace_back(c); } ); }};$results = array_map( fn($user) => [ 'name' => $user['name'], 'email' => strtolower($user['email']), 'score' => array_sum($user['grades']) / count($user['grades']), ], array_filter( $users, fn($u) => $u['active'] && count($u['grades']) > 0 ));Feature Support Matrix
Quick reference showing which languages support each feature.
| Language | Variable Declaration | If/Else | Loops | Functions | Structs | Pattern Matching | Error Handling | String Interpolation | List Operations | Signature Idiom |
|---|---|---|---|---|---|---|---|---|---|---|
| C Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ |
| C# Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| C++ Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ |
| Clojure Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Dart Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Elixir Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| F# Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Gleam Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Go Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ |
| Haskell Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Java Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ |
| JavaScript Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ |
| Julia Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Kotlin Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Lisp Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Lua Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ |
| OCaml Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| PHP Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ |
| Python Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| R Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ |
| Ruby Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Rust Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Scala Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Swift Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| TypeScript Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Zig Beauty Index profile | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ |