YAML Explicit Keys and YS
Did you know that in YAML you can write:
? foo
: bar
instead of:
foo: bar
The ?
is called an explicit key indicator.
But why would you want to use it?
It's not often useful in YAML config files, but it is actually useful in YS code.
Explicit Keys in YAML🔗
In YAML, a mapping key doesn't have to be a string. It can be any node.
In flow mode, we could write:
{ {foo: 1, bar: 2}: baz }
Where {foo: 1, bar: 2}
is a mapping node that is also a mapping key.
How would we write that in block (indented) mode?
With explicit key syntax!
? foo: 1
bar: 2
: baz
Note that when you use ?
the :
has to be on a different line and in the same
column as the ?
.
Explicit Keys in YS🔗
There's another reason to use explicit keys in YAML.
String keys need to be encoded on a single line, even if they are quoted. String values can be multi-line, but string keys cannot.
this is a very long string key for example:
this is a very
long string value
for example
It's not a common problem to solve in YAML, but in YS it comes up more often.
In Yesterday's blog post I showed you a YS program
with a loop
function that started like this:
loop i 0 [x y], [0 0], data {}, [minx maxx miny maxy] [0 0 0 0]:
dir =: i-to-dir(i)
nx ny =: +
...
That line isn't terribly long, but it could be if we had used longer variable
names or more arguments to the loop
function.
We haven't covered the YS loop
function in detail yet, but it starts with a
set of symbol bindings and their initial values.
Then in the tail position of the body we either recur
with a new value for
binding or we return the result.
In YS the word loop
and its bindings need to be on the key side and the rest
of the body needs to be on the value side.
So we ended up with a long line that was hard to read (even though we used
commas to separate the bindings).
It might be nicer to see each binding on a separate line.
Of course we'd have to use YAML explicit keys to do that!
? loop
i 0
[x y] [0 0]
data {}
[minx maxx miny maxy] [0 0 0 0]
: dir =: i-to-dir(i)
nx ny =: +
...
YAML is often criticized for having too many features that are rarely used.
That's fair, but I'd like to point out that YS has put many of those features to good use.
YS is not just about trying to encode Clojure/Lisp forms into YAML...
It's about doing that and making it actually be pretty awesome!