← SPL reference

Keymaps & custom string sort

A keymap attaches ordered per-character numeric weights to a class. Use string.sorted to reorder the characters of a string by those weights (stable sort; optional greatest-to-least via reverse). Interpreter: someProgrammingLanguage/main.py.

Syntax colors in this guide

1. Register a keymap inside a class

Only inside classDefine: call keymap.createKeyMap(name); to bind a handle (e.g. key1) to the current class. Then define the weight table with keymapDefine.keymap: and a single hash literal { ... } statement.

classDefine.keys():
keymap.createKeyMap(key1);
string1.setVar("");
string1.public();
constructorDefine():
end;
keymapDefine.keymap:
{
  "a": 1,
  "b": string.length(string1)
};
end;
end;

2. keymap.curr & order of keys

Values are evaluated in the order they appear in the hash. While each expression runs, keymap.curr is the partial table built so far. Read another character’s weight with hash.getValue("x", keymap.curr) (the parser does not support keymap.curr.getValue(...)).

3. string.sorted

Pass the string to sort, then the keymap variable, then reverse flag (0 / 1 or false / true). Named arguments use the same <- token as assignment:

print.string(string.sorted(s, key <- key1, reverse <- false));

Every character that appears in s must have a row in the keymap. For sorting, the runtime fills string1, string, or s on the synthetic instance with s when those fields exist, and sets keymap to the handle.

4. Conditionals as values

In expression position, test.ifTrue returns the condition, not the branch value. Prefer a single expression (e.g. math.multiply(test.isLess(a, b), 2)) for numeric branches.

5. Full example (repository)

Runnable copy: examples/keymap/keymap_sort.spl — prints acb then ac for the built-in demo weights.

#comment: see examples/keymap/keymap_sort.spl in the repo;

print.string(string.sorted(string2, key <- key1, reverse <- false));

See also: Classes & OOP, Data types ({ } hashes), and the reference filter Keymaps & custom string sort on the main page.