instruction stringlengths 80 309 | output stringlengths 191 774 | category stringlengths 17 32 | task stringlengths 7 21 |
|---|---|---|---|
Using @stdlib/uuid, write a Hemlock program to use equals(), compare(), and is_nil() to classify relationships between a handful of hard-coded UUID strings. | import { equals, compare, is_nil } from "@stdlib/uuid";
let a = "550e8400-e29b-41d4-a716-446655440000";
let b = "550E8400-E29B-41D4-A716-446655440000";
let c = "00000000-0000-0000-0000-000000000000";
let d = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
print(`equals(a, b): ${equals(a, b)}`);
print(`equals(a, d): ${equals(... | stdlib/uuid/hinted | compare_equals |
What imports do I need from @stdlib/strings to truncate a list of article titles to 30 characters with '...' suffix and print each? Write the full Hemlock program. | import { truncate } from "@stdlib/strings";
let titles = [
"A Short Title",
"This one is medium length here",
"A significantly longer headline that should be clipped when shown in a compact list"
];
for (t in titles) {
print(truncate(t, 30, "..."));
} | stdlib/strings/import-recall | truncate_summary |
Write a Hemlock program to compute the arithmetic mean and population standard deviation of a list of numbers and print each rounded to 2 decimals. Use @stdlib/math. | import { sqrt } from "@stdlib/math";
import { to_fixed } from "@stdlib/decimal";
fn mean(xs: array): f64 {
let s = 0.0;
for (x in xs) { s += x; }
return s / xs.length;
}
fn stddev(xs: array): f64 {
let m = mean(xs);
let sq = 0.0;
for (x in xs) {
let d = x - m;
sq += d * d;
... | stdlib/math/hinted | mean_stddev |
Show the imports and Hemlock code to use replace_all with REG_EXTENDED to collapse runs of spaces into a single space and to replace every digit run with 'NUM', then print both results. | import { replace_all, REG_EXTENDED } from "@stdlib/regex";
let messy = "hello world foo bar";
let clean = replace_all(" +", messy, " ", REG_EXTENDED);
print(clean);
let cleaned = replace_all("[0-9]+", "order 123 and 456 done", "NUM", REG_EXTENDED);
print(cleaned); | stdlib/regex/import-recall | replace_whitespace |
Show the imports and Hemlock code to count word occurrences in a space-separated string using a hash map, then print each word and its count. | import { HashMap } from "@stdlib/collections";
fn word_count(text: string) {
let counts = HashMap();
for (w in text.split(" ")) {
if (counts.has(w)) {
counts.set(w, counts.get(w) + 1);
} else {
counts.set(w, 1);
}
}
return counts;
}
let counts = word_cou... | stdlib/collections/import-recall | hashmap_word_count |
Solve this in Hemlock: truncate a list of article titles to 30 characters with '...' suffix and print each. | import { truncate } from "@stdlib/strings";
let titles = [
"A Short Title",
"This one is medium length here",
"A significantly longer headline that should be clipped when shown in a compact list"
];
for (t in titles) {
print(truncate(t, 30, "..."));
} | stdlib/strings/unhinted | truncate_summary |
In Hemlock (importing from @stdlib/math), seed the RNG to 42, roll ten six-sided dice using floor(rand_range(1.0, 7.0)), print the rolls comma-separated, and print the sum. | import { rand_range, floor, seed } from "@stdlib/math";
seed(42);
let rolls = [];
for (let i = 0; i < 10; i++) {
rolls.push(floor(rand_range(1.0, 7.0)));
}
print(`rolls: ${rolls.join(", ")}`);
let sum = 0;
for (r in rolls) { sum += r; }
print(`sum: ${sum}`); | stdlib/math/hinted | seeded_dice |
What imports do I need from @stdlib/toml to parse a TOML config with a nested [app.limits] table and read four dotted paths using get()? Write the full Hemlock program. | import { parse, get } from "@stdlib/toml";
let doc = parse("[app]\nname = \"hemlock\"\nversion = \"2.0.0\"\n\n[app.limits]\nmax_users = 1000\nmax_memory_mb = 512\n");
print(get(doc, "app.name"));
print(get(doc, "app.version"));
print(get(doc, "app.limits.max_users"));
print(get(doc, "app.limits.max_memory_mb")); | stdlib/toml/import-recall | get_nested |
What imports do I need from @stdlib/decimal to build a CSV document using StringBuilder (sb_new/sb_append/sb_to_string) and print the result? Write the full Hemlock program. | import { sb_new, sb_append, sb_to_string } from "@stdlib/decimal";
let rows = [
["name", "age", "city"],
["Alice", "30", "NYC"],
["Bob", "25", "LA"],
["Charlie", "40", "Chicago"]
];
let sb = sb_new();
for (row in rows) {
sb_append(sb, row.join(","));
sb_append(sb, "\n");
}
print(sb_to_string(s... | stdlib/decimal/import-recall | stringbuilder_csv |
In Hemlock, parse a compact JSON config string and print it pretty-printed with 2-space indentation. | import { parse, pretty } from "@stdlib/json";
let raw = "{\"server\":{\"host\":\"localhost\",\"port\":8080},\"features\":[\"auth\",\"logging\"]}";
let cfg = parse(raw);
print(pretty(cfg, 2)); | stdlib/json/unhinted | pretty_config |
In Hemlock (importing from @stdlib/math), print floor, ceil, round, and trunc of a handful of positive and negative decimals so the difference between the four modes is visible. | import { floor, ceil, round, trunc } from "@stdlib/math";
let values = [2.3, 2.5, 2.7, -2.3, -2.5, -2.7];
for (v in values) {
print(`${v}: floor=${floor(v)} ceil=${ceil(v)} round=${round(v)} trunc=${trunc(v)}`);
} | stdlib/math/hinted | rounding_modes |
Solve this in Hemlock: use test() with REG_EXTENDED to validate a few candidate email addresses against a pattern and print true/false for each. | import { test, REG_EXTENDED } from "@stdlib/regex";
let pattern = "^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
let inputs = [
"alice@example.com",
"bob.smith+tag@mail.co",
"not-an-email",
"missing@tld",
"@nope.com"
];
for (addr in inputs) {
print(`${addr} -> ${test(pattern, addr, REG_EX... | stdlib/regex/unhinted | email_test |
Show the imports and Hemlock code to parse a CSV string into rows, print each row joined with ' | ', then re-serialize with stringify(). | import { parse, stringify } from "@stdlib/csv";
let text = "name,age,city\nAlice,30,NYC\nBob,25,LA\nCharlie,40,Chicago";
let rows = parse(text);
print(`rows: ${rows.length}`);
for (row in rows) {
print(row.join(" | "));
}
print("--- re-serialized ---");
print(stringify(rows)); | stdlib/csv/import-recall | parse_stringify |
Show the imports and Hemlock code to normalize a handful of messy paths (redundant slashes, '..' and '.') using normalize() and also print is_absolute() for each. | import { normalize, is_absolute } from "@stdlib/path";
let paths = [
"/a/b/../c/./d",
"./foo/bar",
"/usr//local///bin",
"/tmp/"
];
for (p in paths) {
print(`${p} -> ${normalize(p)} (absolute=${is_absolute(p)})`);
} | stdlib/path/import-recall | normalize |
Show the imports and Hemlock code to starting from 2026-01-01, compute dates +7 days, +30 days, and +365 days using add_days, then print diff_days between first and last. | import { from_date } from "@stdlib/datetime";
let start = from_date(2026, 1, 1);
let week = start.add_days(7);
let month = start.add_days(30);
let year = start.add_days(365);
print(`start: ${start.to_date_string()}`);
print(`+7d: ${week.to_date_string()}`);
print(`+30d: ${month.to_date_string()}`);
print(`+36... | stdlib/datetime/import-recall | date_arithmetic |
In Hemlock, build a playlist in a LinkedList using append, prepend, and insert; iterate by index to print each item; print contains/index_of checks; then remove the head, reverse in place, and print the final order. | import { LinkedList } from "@stdlib/collections";
let playlist = LinkedList();
playlist.append("intro");
playlist.append("verse");
playlist.append("outro");
playlist.insert(2, "chorus");
playlist.prepend("silence");
print(`size: ${playlist.size}`);
for (let i = 0; i < playlist.size; i++) {
print(`${i}: ${playlist... | stdlib/collections/unhinted | linkedlist_playlist |
What imports do I need from @stdlib/args to parse a synthetic argv like ['script.hml', 'build', '--verbose', '--output', 'out.txt', 'src/main.hml'] and print the flag, an option with default, and the positionals? Write the full Hemlock program. | import { parse, has_flag, get_option, get_positionals } from "@stdlib/args";
let argv = ["script.hml", "build", "--verbose", "--output", "out.txt", "src/main.hml"];
let parsed = parse(argv);
print(`verbose: ${has_flag(parsed, "verbose")}`);
print(`output: ${get_option(parsed, "output", "default.txt")}`);
print(`targ... | stdlib/args/import-recall | parse_flags |
Write a Hemlock program to check whether a list of versions satisfies the caret range '^1.2.0' and then print patch/minor/major increments of 1.2.3. Use @stdlib/semver. | import { satisfies, increment } from "@stdlib/semver";
let versions = ["1.0.0", "1.2.5", "1.3.0", "2.0.0-rc.1", "2.0.0"];
let range = "^1.2.0";
for (v in versions) {
print(`${v} satisfies ${range}: ${satisfies(v, range)}`);
}
print("---");
print(`1.2.3 -> patch: ${increment("1.2.3", "patch")}`);
print(`1.2.3 -> ... | stdlib/semver/hinted | satisfies_range |
Solve this in Hemlock: parse a full filesystem path into {root, dir, base, name, ext} components, print each field, and reassemble via format(). | import { parse, format } from "@stdlib/path";
let p = parse("/home/alice/docs/report.pdf");
print(`root: ${p.root}`);
print(`dir: ${p.dir}`);
print(`base: ${p.base}`);
print(`name: ${p.name}`);
print(`ext: ${p.ext}`);
let rebuilt = format(p);
print(`rebuilt: ${rebuilt}`); | stdlib/path/unhinted | parse_format |
What imports do I need from @stdlib/testing to build a tiny test suite with two describe() blocks covering arithmetic and strings, using expect(x).to_equal(y), and call run() to print the report? Write the full Hemlock program. | import { describe, test, expect, run } from "@stdlib/testing";
describe("arithmetic", fn() {
test("addition", fn() {
expect(2 + 3).to_equal(5);
});
test("subtraction", fn() {
expect(10 - 4).to_equal(6);
});
});
describe("strings", fn() {
test("concat", fn() {
expect("foo" +... | stdlib/testing/import-recall | simple_suite |
In Hemlock (importing from @stdlib/math), clamp a list of sensor readings into the range [0, 100] and print each clamped value, tracking min/max of the raw readings in the same loop and printing the raw range and clamp range at the end. | import { clamp, min, max } from "@stdlib/math";
let readings = [-5, 3, 12, 87, 150, 99, 0];
let lo = 0;
let hi = 100;
let lowest = readings[0];
let highest = readings[0];
for (r in readings) {
print(`${r} -> ${clamp(r, lo, hi)}`);
lowest = min(lowest, r);
highest = max(highest, r);
}
print(`raw range: [$... | stdlib/math/hinted | clamp_bounds |
Using @stdlib/matrix, write a Hemlock program to compute and print det() and trace() for a 2x2 and a 3x3 matrix constructed via from_rows(). | import { from_rows } from "@stdlib/matrix";
let m1 = from_rows([[1, 2], [3, 4]]);
let m2 = from_rows([[2, 0, 1], [3, 1, 0], [0, 4, 2]]);
print(`det(2x2): ${m1.det()}`);
print(`trace(2x2): ${m1.trace()}`);
print(`det(3x3): ${m2.det()}`);
print(`trace(3x3): ${m2.trace()}`); | stdlib/matrix/hinted | determinant_trace |
Write a Hemlock program to count word occurrences in a space-separated string using a hash map, then print each word and its count. | import { HashMap } from "@stdlib/collections";
fn word_count(text: string) {
let counts = HashMap();
for (w in text.split(" ")) {
if (counts.has(w)) {
counts.set(w, counts.get(w) + 1);
} else {
counts.set(w, 1);
}
}
return counts;
}
let counts = word_cou... | stdlib/collections/unhinted | hashmap_word_count |
In Hemlock (importing from @stdlib/collections), build a LinkedList, Queue, and Stack; call to_array() on each and pipe the result through array sort/map/filter/reverse, printing each transformed result. | import { LinkedList, Queue, Stack } from "@stdlib/collections";
let ll = LinkedList();
ll.append(3); ll.append(1); ll.append(4); ll.append(1); ll.append(5);
let sorted = ll.to_array();
sorted.sort();
print(`sorted: ${sorted.join(",")}`);
let doubled = ll.to_array().map(fn(x) { return x * 2; });
print(`doubled: ${dou... | stdlib/collections/hinted | to_array_pipelines |
What imports do I need from @stdlib/math to print cos(a) and sin(a) at five angles around the unit circle (0, PI/4, PI/2, PI, 3PI/2), each formatted to 4 decimals? Write the full Hemlock program. | import { sin, cos, PI } from "@stdlib/math";
import { to_fixed } from "@stdlib/decimal";
let angles = [0.0, PI / 4.0, PI / 2.0, PI, 3.0 * PI / 2.0];
for (a in angles) {
let x = cos(a);
let y = sin(a);
print(`(${to_fixed(x, 4)}, ${to_fixed(y, 4)})`);
} | stdlib/math/import-recall | trig_unit_circle |
Show the imports and Hemlock code to parse several ISO-8601 timestamps with parse_iso() and print each as 'weekday month-name time'. | import { parse_iso } from "@stdlib/datetime";
let inputs = [
"2026-01-15T10:00:00Z",
"2026-04-17T14:30:45Z",
"2025-12-31T23:59:59Z"
];
for (s in inputs) {
let dt = parse_iso(s);
print(`${s} -> ${dt.weekday_name()} ${dt.month_name()} ${dt.to_time_string()}`);
} | stdlib/datetime/import-recall | parse_iso |
In Hemlock, enqueue three print jobs, peek at the front, then dequeue and print each job until the Queue is empty. | import { Queue } from "@stdlib/collections";
let jobs = Queue();
jobs.enqueue({ id: 1, doc: "report.pdf" });
jobs.enqueue({ id: 2, doc: "invoice.pdf" });
jobs.enqueue({ id: 3, doc: "notes.txt" });
print(`queued: ${jobs.size}`);
print(`next up: ${jobs.peek().doc}`);
while (!jobs.is_empty()) {
let j = jobs.dequeue... | stdlib/collections/unhinted | queue_print_jobs |
Solve this in Hemlock: print a few integers in hexadecimal, octal, and binary using to_hex, to_oct, and to_bin. | import { to_hex, to_bin, to_oct } from "@stdlib/decimal";
let values = [0, 10, 255, 1024, 65535];
for (v in values) {
print(`${v}: hex=${to_hex(v)} oct=${to_oct(v)} bin=${to_bin(v)}`);
} | stdlib/decimal/unhinted | int_base_convert |
Write a Hemlock program to parse a synthetic argv like ['script.hml', 'build', '--verbose', '--output', 'out.txt', 'src/main.hml'] and print the flag, an option with default, and the positionals. | import { parse, has_flag, get_option, get_positionals } from "@stdlib/args";
let argv = ["script.hml", "build", "--verbose", "--output", "out.txt", "src/main.hml"];
let parsed = parse(argv);
print(`verbose: ${has_flag(parsed, "verbose")}`);
print(`output: ${get_option(parsed, "output", "default.txt")}`);
print(`targ... | stdlib/args/unhinted | parse_flags |
Write a Hemlock program to zip names with ages into pairs and print each as 'name is age', then use unzip() to split them back into two parallel arrays. | import { zip, unzip } from "@stdlib/iter";
let names = ["Alice", "Bob", "Charlie"];
let ages = [30, 25, 40];
let pairs = zip(names, ages);
for (p in pairs) {
print(`${p[0]} is ${p[1]}`);
}
let split = unzip(pairs);
print(`names: ${split[0].join(", ")}`);
print(`ages: ${split[1].join(", ")}`); | stdlib/iter/unhinted | zip_unzip |
Show the imports and Hemlock code to check a list of candidate UUID strings with is_valid(), and for each valid one print to_upper(), to_lower(), and is_nil(). | import { is_valid, is_nil, to_upper, to_lower } from "@stdlib/uuid";
let samples = [
"550e8400-e29b-41d4-a716-446655440000",
"00000000-0000-0000-0000-000000000000",
"not-a-uuid",
"550E8400-E29B-41D4-A716-446655440000"
];
for (s in samples) {
if (is_valid(s)) {
print(`valid: ${s}`);
... | stdlib/uuid/import-recall | validate_static |
Solve this in Hemlock: parse a CSV of users into objects, filter rows where status is 'active', and re-emit them using stringify_objects(). | import { parse_objects, stringify_objects } from "@stdlib/csv";
let text = "user,status\nalice,active\nbob,inactive\ncarol,active\ndave,banned";
let users = parse_objects(text);
let active = [];
for (u in users) {
if (u.status == "active") { active.push(u); }
}
print(`active: ${active.length}`);
print(stringify_... | stdlib/csv/unhinted | filter_active |
Using @stdlib/bytes, write a Hemlock program to convert a u16 port and a u32 IPv4 address to network byte order with htons/htonl, then back with ntohs/ntohl, printing each step in hex. | import { htons, htonl, ntohs, ntohl } from "@stdlib/bytes";
import { to_hex } from "@stdlib/decimal";
let port: u16 = 8080;
let ip: u32 = 0xC0A80101; // 192.168.1.1
let port_net = htons(port);
let ip_net = htonl(ip);
print(`host port ${port} -> network ${to_hex(port_net)}`);
print(`host ip ${to_hex(ip)} -> ne... | stdlib/bytes/hinted | network_order |
In Hemlock (importing from @stdlib/compression), gzip a repeating string, then gunzip it, printing original byte length, whether the round-trip matches, and the restored byte length. | import { gzip, gunzip } from "@stdlib/compression";
let original = "Hemlock is a systems scripting language. " +
"Hemlock is a systems scripting language. " +
"Hemlock is a systems scripting language.";
let compressed = gzip(original);
let restored = gunzip(compressed);
print(`original ... | stdlib/compression/hinted | gzip_roundtrip |
What imports do I need from @stdlib/strings to split a multi-line document with lines() and words(), printing each numbered line and the overall word count? Write the full Hemlock program. | import { lines, words } from "@stdlib/strings";
let doc = "The quick brown fox\njumps over the lazy dog\nover and over again";
let line_arr = lines(doc);
print(`lines: ${line_arr.length}`);
for (let i = 0; i < line_arr.length; i++) {
print(` [${i}] ${line_arr[i]}`);
}
let word_arr = words(doc);
print(`words: ${... | stdlib/strings/import-recall | lines_and_words |
Using @stdlib/hash, write a Hemlock program to hash a handful of diverse inputs (empty string, short string, long sentence, password, composite record) with sha256() and md5(), prefixing each printed digest with the input's length. | import { sha256, md5 } from "@stdlib/hash";
let inputs = [
"",
"hello",
"The quick brown fox jumps over the lazy dog",
"password123",
"user:alice,role:admin"
];
for (s in inputs) {
print(`sha256(${s.length}): ${sha256(s)}`);
}
print("---");
for (s in inputs) {
print(`md5(${s.length}): ... | stdlib/hash/hinted | sha256_hex |
Show the imports and Hemlock code to use a Stack to check whether several bracket expressions are balanced and print true/false for each. | import { Stack } from "@stdlib/collections";
fn matches(open: rune, close: rune): bool {
if (open == '(' && close == ')') { return true; }
if (open == '[' && close == ']') { return true; }
if (open == '{' && close == '}') { return true; }
return false;
}
fn balanced(expr: string): bool {
let s = S... | stdlib/collections/import-recall | stack_balanced_parens |
Show the imports and Hemlock code to deduplicate a list of tags using a Set, print the sorted unique tags, and show union/intersection with a second Set. | import { Set } from "@stdlib/collections";
let raw_tags = ["urgent", "bug", "urgent", "feature", "bug", "docs", "feature"];
let tags = Set();
for (t in raw_tags) { tags.add(t); }
print(`unique tag count: ${tags.size}`);
let values = tags.values();
values.sort();
print(`tags: ${values.join(", ")}`);
let other = Set()... | stdlib/collections/import-recall | set_unique_tags |
In Hemlock (importing from @stdlib/bytes), byte-swap a u16, u32, and u64 using bswap16/bswap32/bswap64 and print each 'before -> after' pair in hex. | import { bswap16, bswap32, bswap64 } from "@stdlib/bytes";
import { to_hex } from "@stdlib/decimal";
let v16: u16 = 0xABCD;
let v32: u32 = 0x12345678;
let v64: u64 = 0x0123456789ABCDEF;
print(`${to_hex(v16)} -> ${to_hex(bswap16(v16))}`);
print(`${to_hex(v32)} -> ${to_hex(bswap32(v32))}`);
print(`${to_hex(v64)} -> ${t... | stdlib/bytes/hinted | byte_swap |
In Hemlock (importing from @stdlib/math), print cos(a) and sin(a) at five angles around the unit circle (0, PI/4, PI/2, PI, 3PI/2), each formatted to 4 decimals. | import { sin, cos, PI } from "@stdlib/math";
import { to_fixed } from "@stdlib/decimal";
let angles = [0.0, PI / 4.0, PI / 2.0, PI, 3.0 * PI / 2.0];
for (a in angles) {
let x = cos(a);
let y = sin(a);
print(`(${to_fixed(x, 4)}, ${to_fixed(y, 4)})`);
} | stdlib/math/hinted | trig_unit_circle |
In Hemlock (importing from @stdlib/regex), use test() with REG_EXTENDED to validate a few candidate email addresses against a pattern and print true/false for each. | import { test, REG_EXTENDED } from "@stdlib/regex";
let pattern = "^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
let inputs = [
"alice@example.com",
"bob.smith+tag@mail.co",
"not-an-email",
"missing@tld",
"@nope.com"
];
for (addr in inputs) {
print(`${addr} -> ${test(pattern, addr, REG_EX... | stdlib/regex/hinted | email_test |
What imports do I need from @stdlib/math to compute compound interest on $1000 at 5% for years 1 through 5 using pow(), and print each yearly balance formatted to 2 decimals? Write the full Hemlock program. | import { pow } from "@stdlib/math";
import { to_fixed } from "@stdlib/decimal";
fn compound(principal: f64, rate: f64, years: i32): f64 {
return principal * pow(1.0 + rate, years);
}
let principal = 1000.0;
let rate = 0.05;
for (let y = 1; y <= 5; y++) {
let value = compound(principal, rate, y);
print(`ye... | stdlib/math/import-recall | compound_interest |
Using @stdlib/strings, write a Hemlock program to truncate a list of article titles to 30 characters with '...' suffix and print each. | import { truncate } from "@stdlib/strings";
let titles = [
"A Short Title",
"This one is medium length here",
"A significantly longer headline that should be clipped when shown in a compact list"
];
for (t in titles) {
print(truncate(t, 30, "..."));
} | stdlib/strings/hinted | truncate_summary |
What imports do I need from @stdlib/math to compute 2D Euclidean distance for a few point pairs and print each result to 4 decimal places? Write the full Hemlock program. | import { sqrt, pow } from "@stdlib/math";
import { to_fixed } from "@stdlib/decimal";
fn distance(x1: f64, y1: f64, x2: f64, y2: f64): f64 {
let dx = x2 - x1;
let dy = y2 - y1;
return sqrt(pow(dx, 2.0) + pow(dy, 2.0));
}
print(to_fixed(distance(0.0, 0.0, 3.0, 4.0), 4));
print(to_fixed(distance(0.0, 0.0, 1... | stdlib/math/import-recall | sqrt_distance |
Show the imports and Hemlock code to gzip a repeating string, then gunzip it, printing original byte length, whether the round-trip matches, and the restored byte length. | import { gzip, gunzip } from "@stdlib/compression";
let original = "Hemlock is a systems scripting language. " +
"Hemlock is a systems scripting language. " +
"Hemlock is a systems scripting language.";
let compressed = gzip(original);
let restored = gunzip(compressed);
print(`original ... | stdlib/compression/import-recall | gzip_roundtrip |
Solve this in Hemlock: parse three version strings into objects, print their components, then use compare() to order a few pairs. | import { parse, compare } from "@stdlib/semver";
let v1 = parse("1.2.3");
let v2 = parse("2.0.0-rc.1");
let v3 = parse("1.2.3-beta+build.42");
print(`v1: major=${v1.major} minor=${v1.minor} patch=${v1.patch}`);
print(`v2: major=${v2.major} prerelease=${v2.prerelease}`);
print(`v3: build=${v3.build}`);
print(`compare... | stdlib/semver/unhinted | parse_compare |
Using @stdlib/path, write a Hemlock program to use path.join to build a path, then extract directory, basename (with and without suffix), and extension. | import { join, dirname, basename, extname } from "@stdlib/path";
let p = join("/var/log", "app/server.log");
print(p);
print(dirname(p));
print(basename(p));
print(basename(p, ".log"));
print(extname(p));
print(extname("README")); | stdlib/path/hinted | join_split |
What imports do I need from @stdlib/encoding to hex-encode and hex-decode a few strings and print the round-trip for each? Write the full Hemlock program. | import { hex_encode, hex_decode } from "@stdlib/encoding";
let inputs = ["Hello", "AB", ""];
for (s in inputs) {
let enc = hex_encode(s);
let dec = hex_decode(enc);
print(`"${s}" -> ${enc} -> "${dec}"`);
} | stdlib/encoding/import-recall | hex_roundtrip |
Show the imports and Hemlock code to parse a TOML document with a top-level key and two tables, print a summary, then re-serialize it. | import { parse, stringify } from "@stdlib/toml";
let input = "title = \"Example\"\n\n[owner]\nname = \"Alice\"\nage = 30\n\n[database]\nserver = \"localhost\"\nport = 8001\n";
let doc = parse(input);
print(`title: ${doc.title}`);
print(`owner: ${doc.owner.name} (age ${doc.owner.age})`);
print(`server: ${doc.database.... | stdlib/toml/import-recall | parse_stringify |
In Hemlock (importing from @stdlib/uuid), check a list of candidate UUID strings with is_valid(), and for each valid one print to_upper(), to_lower(), and is_nil(). | import { is_valid, is_nil, to_upper, to_lower } from "@stdlib/uuid";
let samples = [
"550e8400-e29b-41d4-a716-446655440000",
"00000000-0000-0000-0000-000000000000",
"not-a-uuid",
"550E8400-E29B-41D4-A716-446655440000"
];
for (s in samples) {
if (is_valid(s)) {
print(`valid: ${s}`);
... | stdlib/uuid/hinted | validate_static |
Solve this in Hemlock: define a format_usd helper that wraps to_fixed(x, 2) with a dollar sign, then iterate a list of priced items (including a refund and a large amount) printing each formatted price and the final total. | import { to_fixed } from "@stdlib/decimal";
fn format_usd(amount: f64): string {
return `$${to_fixed(amount, 2)}`;
}
let items = [
{ name: "coffee", price: 4.5 },
{ name: "pastry", price: 3.25 },
{ name: "sandwich", price: 12.99 },
{ name: "sales tax", price: 0.01 },
{ name:... | stdlib/decimal/unhinted | format_currency |
Solve this in Hemlock: url-encode a list of query-parameter key/value pairs and print them joined as a single URL query string. | import { url_encode } from "@stdlib/encoding";
let params = [
{ key: "q", value: "hello world" },
{ key: "lang", value: "en-US" },
{ key: "email", value: "a+b@example.com" }
];
let parts = [];
for (p in params) {
parts.push(`${url_encode(p.key)}=${url_encode(p.value)}`);
}
print(`?${parts.join... | stdlib/encoding/unhinted | url_query |
Using @stdlib/url, write a Hemlock program to round-trip several raw strings through encode_component and decode_component and print each 'raw -> encoded -> decoded' triple. | import { encode_component, decode_component } from "@stdlib/url";
let raw = ["hello world", "a+b=c", "name@host", "résumé"];
for (s in raw) {
let enc = encode_component(s);
let dec = decode_component(enc);
print(`${s} -> ${enc} -> ${dec}`);
} | stdlib/url/hinted | encode_component |
Solve this in Hemlock: set_seed(12345) and print five randint(1,100) values, a choice from a color list, and a sample of 3. | import { set_seed, randint, choice, sample } from "@stdlib/random";
set_seed(12345);
let rolls = [];
for (let i = 0; i < 5; i++) { rolls.push(randint(1, 100)); }
print(`randint: ${rolls.join(", ")}`);
let colors = ["red", "green", "blue", "yellow", "purple"];
print(`choice: ${choice(colors)}`);
print(`sample: ${sa... | stdlib/random/unhinted | seeded_picks |
In Hemlock, parse a nested YAML document and read three dotted paths with get(). | import { parse, get } from "@stdlib/yaml";
let doc = parse("database:\n host: db.local\n credentials:\n user: admin\n pass: secret\nretries: 3\n");
print(get(doc, "database.host"));
print(get(doc, "database.credentials.user"));
print(get(doc, "retries")); | stdlib/yaml/unhinted | get_nested |
In Hemlock (importing from @stdlib/semver), parse three version strings into objects, print their components, then use compare() to order a few pairs. | import { parse, compare } from "@stdlib/semver";
let v1 = parse("1.2.3");
let v2 = parse("2.0.0-rc.1");
let v3 = parse("1.2.3-beta+build.42");
print(`v1: major=${v1.major} minor=${v1.minor} patch=${v1.patch}`);
print(`v2: major=${v2.major} prerelease=${v2.prerelease}`);
print(`v3: build=${v3.build}`);
print(`compare... | stdlib/semver/hinted | parse_compare |
Write a Hemlock program to byte-swap a u16, u32, and u64 using bswap16/bswap32/bswap64 and print each 'before -> after' pair in hex. | import { bswap16, bswap32, bswap64 } from "@stdlib/bytes";
import { to_hex } from "@stdlib/decimal";
let v16: u16 = 0xABCD;
let v32: u32 = 0x12345678;
let v64: u64 = 0x0123456789ABCDEF;
print(`${to_hex(v16)} -> ${to_hex(bswap16(v16))}`);
print(`${to_hex(v32)} -> ${to_hex(bswap32(v32))}`);
print(`${to_hex(v64)} -> ${t... | stdlib/bytes/unhinted | byte_swap |
Using @stdlib/encoding, write a Hemlock program to base64-encode and then base64-decode three sample strings and print each 'original -> encoded -> decoded' line. | import { base64_encode, base64_decode } from "@stdlib/encoding";
let messages = ["Hello, World!", "Hemlock rocks", "foo bar baz"];
for (m in messages) {
let enc = base64_encode(m);
let dec = base64_decode(enc);
print(`${m} -> ${enc} -> ${dec}`);
} | stdlib/encoding/hinted | base64_roundtrip |
In Hemlock (importing from @stdlib/regex), use replace_all with REG_EXTENDED to collapse runs of spaces into a single space and to replace every digit run with 'NUM', then print both results. | import { replace_all, REG_EXTENDED } from "@stdlib/regex";
let messy = "hello world foo bar";
let clean = replace_all(" +", messy, " ", REG_EXTENDED);
print(clean);
let cleaned = replace_all("[0-9]+", "order 123 and 456 done", "NUM", REG_EXTENDED);
print(cleaned); | stdlib/regex/hinted | replace_whitespace |
Show the imports and Hemlock code to use range() with one and three arguments to build two sequences, then print enumerate() pairs of a color list starting at 1. | import { range, enumerate } from "@stdlib/iter";
let nums = range(5);
print(`range(5): ${nums.join(", ")}`);
let stepped = range(0, 20, 4);
print(`range(0,20,4): ${stepped.join(", ")}`);
let labels = ["red", "green", "blue"];
for (p in enumerate(labels, 1)) {
print(`${p[0]}: ${p[1]}`);
} | stdlib/iter/import-recall | range_enumerate |
Show the imports and Hemlock code to deflate_compress a string at levels 1 and 9, print the original byte_length and each compressed buffer's length in bytes, then verify both inflate_decompress results match the original. | import { deflate_compress, inflate_decompress } from "@stdlib/compression";
let text = "banana bandana banana bandana banana bandana banana bandana";
let low = deflate_compress(text, 1);
let high = deflate_compress(text, 9);
print(`original: ${text.byte_length} bytes`);
print(`level 1: ${low.length} bytes`... | stdlib/compression/import-recall | deflate_levels |
What imports do I need from @stdlib/csv to parse a CSV of users into objects, filter rows where status is 'active', and re-emit them using stringify_objects()? Write the full Hemlock program. | import { parse_objects, stringify_objects } from "@stdlib/csv";
let text = "user,status\nalice,active\nbob,inactive\ncarol,active\ndave,banned";
let users = parse_objects(text);
let active = [];
for (u in users) {
if (u.status == "active") { active.push(u); }
}
print(`active: ${active.length}`);
print(stringify_... | stdlib/csv/import-recall | filter_active |
Using @stdlib/csv, write a Hemlock program to parse a CSV of users into objects, filter rows where status is 'active', and re-emit them using stringify_objects(). | import { parse_objects, stringify_objects } from "@stdlib/csv";
let text = "user,status\nalice,active\nbob,inactive\ncarol,active\ndave,banned";
let users = parse_objects(text);
let active = [];
for (u in users) {
if (u.status == "active") { active.push(u); }
}
print(`active: ${active.length}`);
print(stringify_... | stdlib/csv/hinted | filter_active |
Using @stdlib/url, write a Hemlock program to parse a query string with parse_query(), print each name/value, then use get_query_param and set_query_param on a full URL. | import { parse_query, format_query, get_query_param, set_query_param } from "@stdlib/url";
let params = parse_query("page=2&limit=25&sort=date");
for (p in params) {
print(`${p.name} = ${p.value}`);
}
let url = "https://api.example.com/items?page=1";
print(get_query_param(url, "page"));
let updated = set_query_p... | stdlib/url/hinted | query_params |
Show the imports and Hemlock code to use test() with REG_EXTENDED to validate a few candidate email addresses against a pattern and print true/false for each. | import { test, REG_EXTENDED } from "@stdlib/regex";
let pattern = "^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
let inputs = [
"alice@example.com",
"bob.smith+tag@mail.co",
"not-an-email",
"missing@tld",
"@nope.com"
];
for (addr in inputs) {
print(`${addr} -> ${test(pattern, addr, REG_EX... | stdlib/regex/import-recall | email_test |
Show the imports and Hemlock code to parse a nested YAML document and read three dotted paths with get(). | import { parse, get } from "@stdlib/yaml";
let doc = parse("database:\n host: db.local\n credentials:\n user: admin\n pass: secret\nretries: 3\n");
print(get(doc, "database.host"));
print(get(doc, "database.credentials.user"));
print(get(doc, "retries")); | stdlib/yaml/import-recall | get_nested |
Using @stdlib/iter, write a Hemlock program to zip names with ages into pairs and print each as 'name is age', then use unzip() to split them back into two parallel arrays. | import { zip, unzip } from "@stdlib/iter";
let names = ["Alice", "Bob", "Charlie"];
let ages = [30, 25, 40];
let pairs = zip(names, ages);
for (p in pairs) {
print(`${p[0]} is ${p[1]}`);
}
let split = unzip(pairs);
print(`names: ${split[0].join(", ")}`);
print(`ages: ${split[1].join(", ")}`); | stdlib/iter/hinted | zip_unzip |
Show the imports and Hemlock code to shuffle a deck [1..10] with set_seed(7), then reshuffle a fresh copy with the same seed and verify the outputs are identical. | import { set_seed, shuffle } from "@stdlib/random";
set_seed(7);
let deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let shuffled = shuffle(deck);
print(`shuffled: ${shuffled.join(", ")}`);
set_seed(7);
let again = shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
print(`same seed: ${again.join(", ")}`);
print(`deterministic: ${shu... | stdlib/random/import-recall | seeded_shuffle |
Solve this in Hemlock: apply three deep updates to a parsed JSON document using set() (nested object field, array index, and a second-level field), then print the re-serialized JSON. | import { parse, stringify, set } from "@stdlib/json";
let doc = parse("{\"user\":{\"name\":\"Alice\",\"settings\":{\"theme\":\"light\"}},\"counts\":[1,2,3]}");
set(doc, "user.name", "Bob");
set(doc, "user.settings.theme", "dark");
set(doc, "counts.1", 99);
print(stringify(doc)); | stdlib/json/unhinted | set_deep_update |
Write a Hemlock program to build a 2x3 matrix with from_rows, print its transpose row by row, then build a 3x3 identity() and print its rows. | import { from_rows, identity } from "@stdlib/matrix";
let m = from_rows([[1, 2, 3], [4, 5, 6]]);
let t = m.transpose();
for (let r = 0; r < 3; r++) {
print(`t[${r}]: ${t.row(r).join(", ")}`);
}
let I3 = identity(3);
for (let r = 0; r < 3; r++) {
print(`I[${r}]: ${I3.row(r).join(", ")}`);
} | stdlib/matrix/unhinted | transpose_identity |
In Hemlock, allocate one persistent block in an Arena, save() the mark, allocate two temporary blocks, then restore() and print used bytes at each step. | import { Arena } from "@stdlib/arena";
let a = Arena(2048);
let persistent = a.alloc(200);
print(`after persistent: ${a.used} bytes used`);
let mark = a.save();
let temp1 = a.alloc(300);
let temp2 = a.alloc(400);
print(`after temp allocs: ${a.used} bytes used`);
a.restore(mark);
print(`after restore: ${a.used} byte... | stdlib/arena/unhinted | save_restore |
What imports do I need from @stdlib/json to read several dot-path values from a nested JSON-like object using get(), including a missing path with a default? Write the full Hemlock program. | import { get } from "@stdlib/json";
let doc = {
user: {
name: "Alice",
address: { city: "NYC", zip: 10001 }
},
items: [10, 20, 30],
flags: { admin: true }
};
print(get(doc, "user.name"));
print(get(doc, "user.address.city"));
print(get(doc, "items.2"));
print(get(doc, "user.phone", "(n... | stdlib/json/import-recall | get_nested_paths |
Write a Hemlock program to use format() with %s/%d/%.Nf/%x/%o/%b specifiers and width/flag modifiers (%10s, %-10s, %05d, %+d) to print a few lines. Use @stdlib/fmt. | import { format } from "@stdlib/fmt";
print(format("Name: %s, Age: %d", ["Alice", 30]));
print(format("Pi: %.3f", [3.14159]));
print(format("Hex: %x, Oct: %o, Bin: %b", [255, 64, 10]));
print(format("[%10s] [%-10s] [%05d]", ["hi", "hi", 42]));
print(format("%+d vs % d", [42, 42])); | stdlib/fmt/hinted | printf_format |
In Hemlock (importing from @stdlib/assert), use assert, assert_eq, assert_ne, and assert_type to verify a simple add() function and a couple of type checks, then print a success message. | import { assert, assert_eq, assert_ne, assert_type } from "@stdlib/assert";
fn add(a: i32, b: i32): i32 { return a + b; }
assert(add(2, 3) == 5, "2 + 3 should be 5");
assert_eq(add(10, -4), 6);
assert_ne(add(1, 1), 3);
assert_type("hello", "string");
assert_type(42, "i32");
print("all assertions passed"); | stdlib/assert/hinted | basic_checks |
In Hemlock, format a few integers with thousands(), convert byte counts to human units with bytes_size(), and print durations and ordinals. | import { thousands, bytes_size, duration, ordinal } from "@stdlib/fmt";
let nums = [1234, 1234567, 1234567890];
for (n in nums) {
print(`${n} -> ${thousands(n)}`);
}
let sizes = [512, 1500000, 1500000000, 1500000000000];
for (s in sizes) {
print(`${s} bytes -> ${bytes_size(s)}`);
}
print(duration(90));
print... | stdlib/fmt/unhinted | thousands_bytes |
Solve this in Hemlock: parse a full URL with userinfo, port, path, query, and fragment using parse(), then print each component. | import { parse } from "@stdlib/url";
let u = parse("https://user:pass@example.com:8080/api/v2/users?limit=10&sort=name#top");
print(`scheme: ${u.scheme}`);
print(`host: ${u.host}`);
print(`port: ${u.port}`);
print(`path: ${u.path}`);
print(`query: ${u.query}`);
print(`fragment: ${u.fragment}`); | stdlib/url/unhinted | parse_parts |
Show the imports and Hemlock code to parse a full URL with userinfo, port, path, query, and fragment using parse(), then print each component. | import { parse } from "@stdlib/url";
let u = parse("https://user:pass@example.com:8080/api/v2/users?limit=10&sort=name#top");
print(`scheme: ${u.scheme}`);
print(`host: ${u.host}`);
print(`port: ${u.port}`);
print(`path: ${u.path}`);
print(`query: ${u.query}`);
print(`fragment: ${u.fragment}`); | stdlib/url/import-recall | parse_parts |
Solve this in Hemlock: parse several numeric strings using parse_int with different radixes (10, 16, 2, 8) and print each parsed value. | import { parse_int } from "@stdlib/decimal";
print(`"42" base 10 -> ${parse_int("42", 10)}`);
print(`"ff" base 16 -> ${parse_int("ff", 16)}`);
print(`"1010" base 2 -> ${parse_int("1010", 2)}`);
print(`"777" base 8 -> ${parse_int("777", 8)}`);
print(`"-100" base 10 -> ${parse_int("-100", 10)}`); | stdlib/decimal/unhinted | parse_int_bases |
Using @stdlib/json, write a Hemlock program to spread an overrides object over a defaults object to produce a merged configuration, then print the merged JSON. | import { stringify } from "@stdlib/json";
let defaults = { host: "localhost", port: 8080, debug: false, retries: 3 };
let overrides = { port: 9000, debug: true };
let merged = { ...defaults, ...overrides };
print(stringify(merged)); | stdlib/json/hinted | merge_configs |
What imports do I need from @stdlib/csv to parse a CSV and sum the values of a numeric column using get_column() and parse_int()? Write the full Hemlock program. | import { parse, get_column } from "@stdlib/csv";
import { parse_int } from "@stdlib/decimal";
let text = "item,qty,price\napple,10,1\nbread,3,4\nmilk,6,2";
let rows = parse(text);
let qty_col = get_column(rows, 1);
let total = 0;
for (let i = 1; i < qty_col.length; i++) {
total += parse_int(qty_col[i], 10);
}
pri... | stdlib/csv/import-recall | column_sum |
Using @stdlib/math, write a Hemlock program to compute 2D Euclidean distance for a few point pairs and print each result to 4 decimal places. | import { sqrt, pow } from "@stdlib/math";
import { to_fixed } from "@stdlib/decimal";
fn distance(x1: f64, y1: f64, x2: f64, y2: f64): f64 {
let dx = x2 - x1;
let dy = y2 - y1;
return sqrt(pow(dx, 2.0) + pow(dy, 2.0));
}
print(to_fixed(distance(0.0, 0.0, 3.0, 4.0), 4));
print(to_fixed(distance(0.0, 0.0, 1... | stdlib/math/hinted | sqrt_distance |
In Hemlock, compute 2D Euclidean distance for a few point pairs and print each result to 4 decimal places. | import { sqrt, pow } from "@stdlib/math";
import { to_fixed } from "@stdlib/decimal";
fn distance(x1: f64, y1: f64, x2: f64, y2: f64): f64 {
let dx = x2 - x1;
let dy = y2 - y1;
return sqrt(pow(dx, 2.0) + pow(dy, 2.0));
}
print(to_fixed(distance(0.0, 0.0, 3.0, 4.0), 4));
print(to_fixed(distance(0.0, 0.0, 1... | stdlib/math/unhinted | sqrt_distance |
What imports do I need from @stdlib/math to print floor, ceil, round, and trunc of a handful of positive and negative decimals so the difference between the four modes is visible? Write the full Hemlock program. | import { floor, ceil, round, trunc } from "@stdlib/math";
let values = [2.3, 2.5, 2.7, -2.3, -2.5, -2.7];
for (v in values) {
print(`${v}: floor=${floor(v)} ceil=${ceil(v)} round=${round(v)} trunc=${trunc(v)}`);
} | stdlib/math/import-recall | rounding_modes |
Write a Hemlock program to allocate an i32 counter, initialize to 42, then demonstrate a successful and a failed atomic_cas_i32 call, printing whether each swap succeeded and the final value. | import { atomic_cas_i32, atomic_load_i32, atomic_store_i32 } from "@stdlib/atomic";
let p = alloc(4);
atomic_store_i32(p, 42);
let ok1 = atomic_cas_i32(p, 42, 100);
print(`first CAS (expected 42): success=${ok1}, value=${atomic_load_i32(p)}`);
let ok2 = atomic_cas_i32(p, 42, 200);
print(`second CAS (expected 42, but... | stdlib/atomic/unhinted | compare_and_swap |
Using @stdlib/strings, write a Hemlock program to split a multi-line document with lines() and words(), printing each numbered line and the overall word count. | import { lines, words } from "@stdlib/strings";
let doc = "The quick brown fox\njumps over the lazy dog\nover and over again";
let line_arr = lines(doc);
print(`lines: ${line_arr.length}`);
for (let i = 0; i < line_arr.length; i++) {
print(` [${i}] ${line_arr[i]}`);
}
let word_arr = words(doc);
print(`words: ${... | stdlib/strings/hinted | lines_and_words |
Write a Hemlock program to take a few sample strings and print each converted to snake_case, camel_case, pascal_case, and kebab_case. | import { snake_case, camel_case, pascal_case, kebab_case } from "@stdlib/strings";
let inputs = ["hello world", "Hello World", "helloWorld", "hello-world_case"];
for (s in inputs) {
print(`${s}`);
print(` snake: ${snake_case(s)}`);
print(` camel: ${camel_case(s)}`);
print(` pascal: ${pascal_case(... | stdlib/strings/unhinted | case_conversions |
What imports do I need from @stdlib/arena to allocate one persistent block in an Arena, save() the mark, allocate two temporary blocks, then restore() and print used bytes at each step? Write the full Hemlock program. | import { Arena } from "@stdlib/arena";
let a = Arena(2048);
let persistent = a.alloc(200);
print(`after persistent: ${a.used} bytes used`);
let mark = a.save();
let temp1 = a.alloc(300);
let temp2 = a.alloc(400);
print(`after temp allocs: ${a.used} bytes used`);
a.restore(mark);
print(`after restore: ${a.used} byte... | stdlib/arena/import-recall | save_restore |
Show the imports and Hemlock code to parse a query string with parse_query(), print each name/value, then use get_query_param and set_query_param on a full URL. | import { parse_query, format_query, get_query_param, set_query_param } from "@stdlib/url";
let params = parse_query("page=2&limit=25&sort=date");
for (p in params) {
print(`${p.name} = ${p.value}`);
}
let url = "https://api.example.com/items?page=1";
print(get_query_param(url, "page"));
let updated = set_query_p... | stdlib/url/import-recall | query_params |
Show the imports and Hemlock code to set_seed(12345) and print five randint(1,100) values, a choice from a color list, and a sample of 3. | import { set_seed, randint, choice, sample } from "@stdlib/random";
set_seed(12345);
let rolls = [];
for (let i = 0; i < 5; i++) { rolls.push(randint(1, 100)); }
print(`randint: ${rolls.join(", ")}`);
let colors = ["red", "green", "blue", "yellow", "purple"];
print(`choice: ${choice(colors)}`);
print(`sample: ${sa... | stdlib/random/import-recall | seeded_picks |
Write a Hemlock program to hex-encode and hex-decode a few strings and print the round-trip for each. Use @stdlib/encoding. | import { hex_encode, hex_decode } from "@stdlib/encoding";
let inputs = ["Hello", "AB", ""];
for (s in inputs) {
let enc = hex_encode(s);
let dec = hex_decode(enc);
print(`"${s}" -> ${enc} -> "${dec}"`);
} | stdlib/encoding/hinted | hex_roundtrip |
What imports do I need from @stdlib/assert to use assert, assert_eq, assert_ne, and assert_type to verify a simple add() function and a couple of type checks, then print a success message? Write the full Hemlock program. | import { assert, assert_eq, assert_ne, assert_type } from "@stdlib/assert";
fn add(a: i32, b: i32): i32 { return a + b; }
assert(add(2, 3) == 5, "2 + 3 should be 5");
assert_eq(add(10, -4), 6);
assert_ne(add(1, 1), 3);
assert_type("hello", "string");
assert_type(42, "i32");
print("all assertions passed"); | stdlib/assert/import-recall | basic_checks |
Using @stdlib/args, write a Hemlock program to parse a synthetic argv like ['script.hml', 'build', '--verbose', '--output', 'out.txt', 'src/main.hml'] and print the flag, an option with default, and the positionals. | import { parse, has_flag, get_option, get_positionals } from "@stdlib/args";
let argv = ["script.hml", "build", "--verbose", "--output", "out.txt", "src/main.hml"];
let parsed = parse(argv);
print(`verbose: ${has_flag(parsed, "verbose")}`);
print(`output: ${get_option(parsed, "output", "default.txt")}`);
print(`targ... | stdlib/args/hinted | parse_flags |
What imports do I need from @stdlib/collections to build a playlist in a LinkedList using append, prepend, and insert; iterate by index to print each item; print contains/index_of checks; then remove the head, reverse in place, and print the final order? Write the full Hemlock program. | import { LinkedList } from "@stdlib/collections";
let playlist = LinkedList();
playlist.append("intro");
playlist.append("verse");
playlist.append("outro");
playlist.insert(2, "chorus");
playlist.prepend("silence");
print(`size: ${playlist.size}`);
for (let i = 0; i < playlist.size; i++) {
print(`${i}: ${playlist... | stdlib/collections/import-recall | linkedlist_playlist |
What imports do I need from @stdlib/json to parse a JSON array of order records and print the count, total amount, and max amount formatted to 2 decimals? Write the full Hemlock program. | import { parse } from "@stdlib/json";
import { to_fixed } from "@stdlib/decimal";
let raw = "[{\"id\":1,\"amount\":19.99},{\"id\":2,\"amount\":5.50},{\"id\":3,\"amount\":42.00},{\"id\":4,\"amount\":8.25}]";
let orders = parse(raw);
let total = 0.0;
let max_amount = 0.0;
for (o in orders) {
total += o.amount;
... | stdlib/json/import-recall | order_totals |
In Hemlock, parse a CSV string into rows, print each row joined with ' | ', then re-serialize with stringify(). | import { parse, stringify } from "@stdlib/csv";
let text = "name,age,city\nAlice,30,NYC\nBob,25,LA\nCharlie,40,Chicago";
let rows = parse(text);
print(`rows: ${rows.length}`);
for (row in rows) {
print(row.join(" | "));
}
print("--- re-serialized ---");
print(stringify(rows)); | stdlib/csv/unhinted | parse_stringify |
What imports do I need from @stdlib/fmt to format a few integers with thousands(), convert byte counts to human units with bytes_size(), and print durations and ordinals? Write the full Hemlock program. | import { thousands, bytes_size, duration, ordinal } from "@stdlib/fmt";
let nums = [1234, 1234567, 1234567890];
for (n in nums) {
print(`${n} -> ${thousands(n)}`);
}
let sizes = [512, 1500000, 1500000000, 1500000000000];
for (s in sizes) {
print(`${s} bytes -> ${bytes_size(s)}`);
}
print(duration(90));
print... | stdlib/fmt/import-recall | thousands_bytes |
In Hemlock (importing from @stdlib/decimal), print a few integers in hexadecimal, octal, and binary using to_hex, to_oct, and to_bin. | import { to_hex, to_bin, to_oct } from "@stdlib/decimal";
let values = [0, 10, 255, 1024, 65535];
for (v in values) {
print(`${v}: hex=${to_hex(v)} oct=${to_oct(v)} bin=${to_bin(v)}`);
} | stdlib/decimal/hinted | int_base_convert |
Write a Hemlock program to parse several numeric strings using parse_int with different radixes (10, 16, 2, 8) and print each parsed value. Use @stdlib/decimal. | import { parse_int } from "@stdlib/decimal";
print(`"42" base 10 -> ${parse_int("42", 10)}`);
print(`"ff" base 16 -> ${parse_int("ff", 16)}`);
print(`"1010" base 2 -> ${parse_int("1010", 2)}`);
print(`"777" base 8 -> ${parse_int("777", 8)}`);
print(`"-100" base 10 -> ${parse_int("-100", 10)}`); | stdlib/decimal/hinted | parse_int_bases |
Solve this in Hemlock: print cos(a) and sin(a) at five angles around the unit circle (0, PI/4, PI/2, PI, 3PI/2), each formatted to 4 decimals. | import { sin, cos, PI } from "@stdlib/math";
import { to_fixed } from "@stdlib/decimal";
let angles = [0.0, PI / 4.0, PI / 2.0, PI, 3.0 * PI / 2.0];
for (a in angles) {
let x = cos(a);
let y = sin(a);
print(`(${to_fixed(x, 4)}, ${to_fixed(y, 4)})`);
} | stdlib/math/unhinted | trig_unit_circle |
Solve this in Hemlock: use a Stack to check whether several bracket expressions are balanced and print true/false for each. | import { Stack } from "@stdlib/collections";
fn matches(open: rune, close: rune): bool {
if (open == '(' && close == ')') { return true; }
if (open == '[' && close == ']') { return true; }
if (open == '{' && close == '}') { return true; }
return false;
}
fn balanced(expr: string): bool {
let s = S... | stdlib/collections/unhinted | stack_balanced_parens |
Hemlock Apothecary Formulary
Stdlib-focused SFT data for fine-tuning Hemlock-Apothecary-7B — a Hemlock-Codex-7B derivative aimed at closing the L2-Stdlib gap measured on hembench.
A formulary in pharmacology is the reference book listing drug compositions and dosages.
Same idea here: one realistic program per (@stdlib/<module>, task) pair showing
exactly how to compose real Hemlock stdlib calls — right imports, right method names,
right idioms.
Why this dataset exists
Evaluating Hemlock-Codex-7B at Q8_0 zero-shot on hembench surfaced a distinctive
failure mode on L2 (Stdlib): hallucinated method names and missing imports.
Typical misses:
"hello".capitalize()— no such method on Hemlock stringssqrt(x)withoutimport { sqrt } from "@stdlib/math";atomic_load_i32called but never importedobj.iter()— a Pythonism, not a Hemlock API
Compact-doc prompting recovered L2 but hurt other levels by 14–20pts (docs in-prompt pull the fine-tune away from its learned idioms). The Formulary attacks the failure mode through training rather than prompting.
Dataset structure
Each row is a single instruction/output SFT pair:
{
"instruction": "Using @stdlib/math, write a Hemlock program to compute 2D Euclidean distance for a few point pairs and print each result to 4 decimal places.",
"output": "import { sqrt, pow } from \"@stdlib/math\";\nimport { to_fixed } from \"@stdlib/decimal\";\n\nfn distance(x1: f64, y1: f64, x2: f64, y2: f64): f64 {\n ...\n}\n\n...",
"category": "stdlib/math/hinted",
"task": "sqrt_distance"
}
Fields
| Field | Type | Description |
|---|---|---|
instruction |
string | Natural-language task prompt |
output |
string | Complete, runnable Hemlock program |
category |
string | stdlib/<module>/<variant> — useful for filtering or weighting at train time |
task |
string | Short slug identifying the source seed |
Prompt variants
Each of the 83 source seeds is expanded into up to 3 rows so the model learns both correct imports and module recognition:
| Variant | Prompt form | Teaches |
|---|---|---|
hinted |
"Using @stdlib/math, write …" | Exact import syntax when the module is known |
unhinted |
"Write a Hemlock program to …" | Picking the right module from the problem description |
import-recall |
"What imports do I need from @stdlib/math to …?" | Naming exact symbols |
Composition
249 rows across 83 seed programs covering 28 of Hemlock's 53 stdlib modules.
| Module | Seeds | Module | Seeds | Module | Seeds |
|---|---|---|---|---|---|
| math | 8 | datetime | 4 | args | 1 |
| json | 6 | encoding | 3 | assert | 1 |
| collections | 6 | fmt | 3 | async | 1 |
| decimal | 5 | iter | 3 | hash | 1 |
| strings | 5 | matrix | 3 | testing | 1 |
| csv | 4 | path | 3 | ||
| url | 3 | ||||
| atomic | 2 | ||||
| bytes | 2 | ||||
| compression | 2 | ||||
| random | 2 | ||||
| regex | 2 | ||||
| semver | 2 | ||||
| toml | 2 | ||||
| uuid | 2 | ||||
| yaml | 2 |
The remaining 25 modules are mostly I/O or nondeterministic (time, logging,
http, net, fs, process, etc.) — reachable but require sandboxing to keep
seed output reproducible. PRs welcome.
Methodology: parity-first
Every seed program under hemlock/stdlib/**/*.hml is verified to produce
byte-identical output under both Hemlock execution backends:
./hemlock— the tree-walking interpreter./hemlockc— the C code generator, linked against libhemlock_runtime
Divergent programs never enter training data. This constraint is enforced by
make check-seeds in the source repo and runs on every regeneration.
Applying it surfaced 7 real compiler/interpreter parity bugs in the Hemlock runtime that have since been fixed:
- LinkedList iteration miscompile (PR #519)
regex.replace_allsegfault under compiler (PR #520)path.normalizeon../..(PR #521)- toml array element unboxing (d6b2587)
for (x in array)+ stdlib-call type confusion (PR #522)LinkedList.reverse()routing to array path (PR #526)- Generalized array-method dispatch on object receivers (PR #527)
Intended use
Recommended: continued SFT on top of Hemlock-Codex-7B, mixed with a small replay sample (~20%) from Codex's original SFT to prevent catastrophic forgetting on L3/L5.
from datasets import load_dataset
formulary = load_dataset("hemlang/hemlock-apothecary", split="train")
print(len(formulary)) # 249
print(formulary[0])
Concatenate with Codex's SFT for a combined training run:
from datasets import concatenate_datasets, load_dataset
codex = load_dataset("hemlang/hemlock-codex", split="train") # 552 rows
formulary = load_dataset("hemlang/hemlock-apothecary", split="train") # 249 rows
combined = concatenate_datasets([codex, formulary]) # 801 rows
Filter by category to rebalance the mix at train time:
stdlib_only = formulary.filter(lambda r: r["category"].startswith("stdlib/"))
imports_only = formulary.filter(lambda r: r["category"].endswith("/import-recall"))
Limitations
- Small. 83 unique programs is limited coverage; 3× variant expansion is a training-efficiency trick, not a breadth increase.
- Deterministic-output bias. Modules with nondeterministic output (time, logging, random without seed, network, process) are excluded. Models trained on this dataset alone will be weakest on those modules.
- English-only prompts. The Codex base was trained with multilingual data; this dataset is English.
- Hemlock-specific. Useless for anything other than Hemlock-family fine-tunes.
Source repo
Full seed sources, generator, parity-check Makefile, and regen pipeline: hemlang/hemlock-apothecary on GitHub.
- Downloads last month
- 64