Show HN: Programming Language Cup: same tasks in 32 langs, pick the winner
people{{"Grace", 36}, {"Linus", 28}, {"Ada", 36}};
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
people{{"Grace", 36}, {"Linus", 28}, {"Ada", 36}}; std::ranges::sort(people, {}, [](const Person& p) { return std::tie(p.age, p.name); }); for (const auto& p : people) std::cout people = List.of( new Person("Grace", 36), new Person("Linus", 28), new Person("Ada", 36)); List sorted = people.stream() .sorted(Comparator.comparingInt(Person::age).thenComparing(Person::name)) .toList(); sorted.forEach(p -> System.out.println(p.name() + " " + p.age())); } } @@ sort kotlin data class Person(val name: String, val age: Int)
fun main() { val people = listOf(Person("Grace", 36), Person("Linus", 28), Person("Ada", 36)) val sorted = people.sortedWith(compareBy({ it.age }, { it.name })) println(sorted.map { it.name }) // [Linus, Ada, Grace] } @@ sort swift struct Person { let name: String let age: Int }
let people = [ Person(name: "Grace", age: 36), Person(name: "Linus", age: 28), Person(name: "Ada", age: 36), ] let sorted = people.sorted { ($0.age, $0.name) { ("Grace", 36), ("Linus", 28), ("Ada", 36) }; var sorted = people.OrderBy(p => p.Age).ThenBy(p => p.Name); foreach (var (name, age) in sorted) Console.WriteLine($"{name} {age}"); @@ sort ruby people = [["Grace", 36], ["Linus", 28], ["Ada", 36]] sorted = people.sort_by { |name, age| [age, name] } p sorted # [["Linus", 28], ["Ada", 36], ["Grace", 36]] @@ sort php "Grace", "age" => 36], ["name" => "Linus", "age" => 28], ["name" => "Ada", "age" => 36], ]; usort($people, fn($a, $b) => [$a["age"], $a["name"]] [$b["age"], $b["name"]]); echo implode(", ", array_column($people, "name")), "\n"; // Linus, Ada, Grace @@ sort haskell import Data.List (sortOn)
people :: [(String, Int)] people = [("Grace", 36), ("Linus", 28), ("Ada", 36)]
main :: IO () main = print (sortOn ((name, age) -> (age, name)) people) -- [("Linus",28),("Ada",36),("Grace",36)] @@ sort elixir people = [%{name: "Grace", age: 36}, %{name: "Linus", age: 28}, %{name: "Ada", age: 36}]
people |> Enum.sort_by(&{&1.age, &1.name}) |> Enum.map(& &1.name) |> IO.inspect() # ["Linus", "Ada", "Grace"] @@ sort lua local people = { { name = "Grace", age = 36 }, { name = "Linus", age = 28 }, { name = "Ada", age = 36 }, }
table.sort(people, function(a, b) if a.age ~= b.age then return a.age people = [ (name: 'Grace', age: 36), (name: 'Linus', age: 28), (name: 'Ada', age: 36), ]; people.sort((a, b) { final byAge = a.age.compareTo(b.age); return byAge != 0 ? byAge : a.name.compareTo(b.name); }); print(people.map((p) => p.name).toList()); // [Linus, Ada, Grace] } @@ sort scala case class Person(name: String, age: Int)
@main def run(): Unit = val people = List(Person("Grace", 36), Person("Linus", 28), Person("Ada", 36)) val sorted = people.sortBy(p => (p.age, p.name)) println(sorted.map(_.name)) // List(Linus, Ada, Grace) @@ sort zig const std = @import("std");
const Person = struct { name: []const u8, age: u32 };
fn lessThan(: void, a: Person, b: Person) bool { if (a.age != b.age) return a.age (p.age, p.name)) println([p.name for p in sorted]) # ["Linus", "Ada", "Grace"] @@ sort r people 'Grace', age => 36 }, { name => 'Linus', age => 28 }, { name => 'Ada', age => 36 }, ); my @sorted = sort { $a->{age} $b->{age} or $a->{name} cmp $b->{name} } @people; say join ', ', map { $->{name} } @sorted; # Linus, Ada, Grace @@ sort clojure (def people [{:name "Grace" :age 36} {:name "Linus" :age 28} {:name "Ada" :age 36}])
(->> people (sort-by (juxt :age :name)) (map :name) println) ; (Linus Ada Grace) @@ sort fsharp type Person = { Name: string; Age: int }
let people = [ { Name = "Grace"; Age = 36 } { Name = "Linus"; Age = 28 } { Name = "Ada"; Age = 36 } ]
people |> List.sortBy (fun p -> p.Age, p.Name) |> List.map (fun p -> p.Name) |> printfn "%A" // ["Linus"; "Ada"; "Grace"] @@ sort ocaml type person = { name : string; age : int }
let people = [ { name = "Grace"; age = 36 }; { name = "Linus"; age = 28 }; { name = "Ada"; age = 36 } ]
let () = people |> List.sort (fun a b -> compare (a.age, a.name) (b.age, b.name)) |> List.iter (fun p -> Printf.printf "%s %d\n" p.name p.age) @@ sort erlang #!/usr/bin/env escript main(_) -> People = [{"Grace", 36}, {"Linus", 28}, {"Ada", 36}], Sorted = lists:sort(fun({N1, A1}, {N2, A2}) -> {A1, N1} = list.sort(fn(a, b) { int.compare(a.age, b.age) |> order.break_tie(string.compare(a.name, b.name)) }) |> list.map(fn(p) { p.name }) |> string.join(", ") |> io.println // Linus, Ada, Grace } @@ sort bash #!/usr/bin/env bash people=("Grace 36" "Linus 28" "Ada 36") printf '%s\n' "${people[@]}" | sort -k2,2n -k1,1 | cut -d' ' -f1
Linus
Ada
Grace
@@ sort objc #import
int main(void) { @autoreleasepool { NSArray *people = @[ @{@"name": @"Grace", @"age": @36}, @{@"name": @"Linus", @"age": @28}, @{@"name": @"Ada", @"age": @36}, ]; NSArray *sorted = [people sortedArrayUsingDescriptors:@[ [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES], ]]; for (NSDictionary *p in sorted) { printf("%s %d\n", [p[@"name"] UTF8String], [p[@"age"] intValue]); } } return 0; } @@ sort lisp (defstruct person name age)
(defun person = {}; for (const word of text.split(" ")) { counts[word] = (counts[word] ?? 0) + 1; } console.log(counts); // { the: 3, cat: 1, and: 2, hat: 1, bat: 1 } @@ wordcount rust use std::collections::HashMap;
fn main() { let text = "the cat and the hat and the bat"; let mut counts: HashMap = HashMap::new(); for word in text.split_whitespace() { *counts.entry(word).or_insert(0) += 1; } println!("{counts:?}"); } @@ wordcount go package main
import ( "fmt" "strings" )
func main() { text := "the cat and the hat and the bat" counts := make(map[string]int) for _, word := range strings.Fields(text) { counts[word]++ } fmt.Println(counts) // map[and:2 bat:1 cat:1 hat:1 the:3] } @@ wordcount c #include #include
int main(void) { char text[] = "the cat and the hat and the bat"; char *words[32]; int counts[32], unique = 0;
for (char *w = strtok(text, " "); w; w = strtok(NULL, " ")) { int i = 0; while (i #include #include #include
int main() { std::istringstream text("the cat and the hat and the bat"); std::map counts; for (std::string word; text >> word;) ++counts[word]; for (const auto& [word, n] : counts) std::cout counts = Arrays.stream(text.split(" ")) .collect(Collectors.groupingBy(w -> w, TreeMap::new, Collectors.counting())); System.out.println(counts); // {and=2, bat=1, cat=1, hat=1, the=3} } } @@ wordcount kotlin fun main() { val text = "the cat and the hat and the bat" val counts = text.split(" ").groupingBy { it }.eachCount() println(counts) // {the=3, cat=1, and=2, hat=1, bat=1} } @@ wordcount swift let text = "the cat and the hat and the bat" var counts: [Substring: Int] = [:] for word in text.split(separator: " ") { counts[word, default: 0] += 1 } print(counts) @@ wordcount csharp var text = "the cat and the hat and the bat"; var counts = text.Split(' ') .GroupBy(w => w) .ToDictionary(g => g.Key, g => g.Count()); foreach (var (word, n) in counts) Console.WriteLine($"{word} {n}"); @@ wordcount ruby text = "the cat and the hat and the bat" counts = text.split.tally p counts # {"the" => 3, "cat" => 1, "and" => 2, "hat" => 1, "bat" => 1} @@ wordcount php String.split() |> Enum.frequencies() |> IO.inspect()
%{"and" => 2, "bat" => 1, "cat" => 1, "hat" => 1, "the" => 3}
@@ wordcount lua local text = "the cat and the hat and the bat" local counts = {} for word in text:gmatch("%S+") do counts[word] = (counts[word] or 0) + 1 end for word, n in pairs(counts) do print(word, n) end @@ wordcount dart void main() { const text = 'the cat and the hat and the bat'; final counts = {}; for (final word in text.split(' ')) { counts.update(word, (n) => n + 1, ifAbsent: () => 1); } print(counts); // {the: 3, cat: 1, and: 2, hat: 1, bat: 1} } @@ wordcount scala @main def wordCount(): Unit = val text = "the cat and the hat and the bat" val counts = text.split(" ").groupMapReduce(identity)(_ => 1)(_ + _) counts.foreach((word, n) => println(s"$word $n")) @@ wordcount zig const std = @import("std");
pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var counts = std.StringArrayHashMap(usize).init(gpa.allocator()); defer counts.deinit();
var words = std.mem.tokenizeScalar(u8, "the cat and the hat and the bat", ' '); while (words.next()) |word| { const entry = try counts.getOrPutValue(word, 0); entry.value_ptr.* += 1; }
const stdout = std.io.getStdOut().writer(); var it = counts.iterator(); while (it.next()) |e| try stdout.print("{s} {d}\n", .{ e.key_ptr., e.value_ptr. }); } @@ wordcount julia text = "the cat and the hat and the bat" counts = Dict{String,Int}() for word in split(text) counts[word] = get(counts, word, 0) + 1 end for (word, n) in counts println(word, " ", n) end @@ wordcount r text "the cat and the hat and the bat" (str/split #" ") frequencies println) ; {the 3, cat 1, and 2, hat 1, bat 1} @@ wordcount fsharp let text = "the cat and the hat and the bat"
text.Split ' ' |> Array.countBy id |> Array.iter (fun (word, n) -> printfn "%s %d" word n) @@ wordcount ocaml module SMap = Map.Make (String)
let () =
"the cat and the hat and the bat"
|> String.split_on_char ' '
|> List.fold_left
(fun m w -> SMap.update w (fun n -> Some (1 + Option.value n ~default:0)) m)
SMap.empty
|> SMap.iter (Printf.printf "%s %d\n")
@@ wordcount erlang
#!/usr/bin/env escript
main(_) ->
Words = string:lexemes("the cat and the hat and the bat", " "),
Counts = lists:foldl(
fun(W, Acc) -> maps:update_with(W, fun(N) -> N + 1 end, 1, Acc) end,
#{}, Words),
maps:foreach(fun(W, N) -> io:format("~s pn", [W, N]) end, Counts).
@@ wordcount nim
import std/[strutils, tables]
let counts = "the cat and the hat and the bat".split.toCountTable for word, n in counts: echo word, " ", n @@ wordcount crystal text = "the cat and the hat and the bat" counts = text.split.tally p counts # {"the" => 3, "cat" => 1, "and" => 2, "hat" => 1, "bat" => 1} @@ wordcount gleam import gleam/dict import gleam/int import gleam/io import gleam/list import gleam/option import gleam/string
pub fn main() { "the cat and the hat and the bat" |> string.split(" ") |> list.fold(dict.new(), fn(counts, word) { dict.upsert(counts, word, fn(n) { option.unwrap(n, 0) + 1 }) }) |> dict.each(fn(word, n) { io.println(word <> " " <> int.to_string(n)) }) } @@ wordcount bash #!/usr/bin/env bash text="the cat and the hat and the bat" tr ' ' '\n'
int main(void) { @autoreleasepool { NSString *text = @"the cat and the hat and the bat"; NSCountedSet *counts = [NSCountedSet setWithArray:[text componentsSeparatedByString:@" "]]; for (NSString *word in counts) { printf("%s %lu\n", word.UTF8String, (unsigned long)[counts countForObject:word]); } } return 0; } @@ wordcount lisp (require :uiop)
(let ((counts (make-hash-table :test #'equal)))
(dolist (word (uiop:split-string "the cat and the hat and the bat"))
(incf (gethash word counts 0)))
(maphash (lambda (word n) (format t "~a a%" word n)) counts))
@@ regex python
import re
text = "Released 2024-03-15, patched 2024-04-02, retired 2025-01-31." for m in re.finditer(r"(\d{4})-(\d{2})-(\d{2})", text): year, month, day = m.groups() print(f"year {year}, month {month}, day {day}") @@ regex javascript const text = "Released 2024-03-15, patched 2024-04-02, retired 2025-01-31."; const dateRe = /(?\d{4})-(?\d{2})-(?\d{2})/g;
for (const { groups: { year, month, day } } of text.matchAll(dateRe)) {
console.log(year ${year}, month ${month}, day ${day});
}
@@ regex typescript
const text = "Released 2024-03-15, patched 2024-04-02, retired 2025-01-31.";
const dateRe: RegExp = /(\d{4})-(\d{2})-(\d{2})/g;
for (const [, year, month, day] of text.matchAll(dateRe)) {
console.log(year ${year}, month ${month}, day ${day});
}
@@ regex rust
// uses: regex
use regex::Regex;
fn main() { let text = "Released 2024-03-15, patched
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。