### Data Mode Example Source: https://yamlscript.org/doc/modes Shows how to start in data mode using the '!ys-0:' tag. This mode allows for the inclusion and execution of YS code. ```bash $ ys --load <(echo ' !ys-0: foo: count: [red, green, blue]') {"foo":{"count":["red","green","blue"]}} ``` -------------------------------- ### Starting in Data Mode with !ys-0 and !data Source: https://yamlscript.org/doc/mode-tags This example demonstrates how to start a YAML document in data mode using `!ys-0` followed by `!data`. The `!ys-0` tag sets up the environment for subsequent mode tags, even if the first document is empty. The expression `6 * 7` is evaluated to `42`. ```yaml !ys-0 --- !data num:: 6 * 7 # 42 ``` -------------------------------- ### Quick Install Script for ys and libys Source: https://yamlscript.org/doc/install Install both 'ys' and 'libys' using a single command-line script. Options include specifying the version, installation prefix, and whether to install only the library or binary. ```bash $ curl https://yamlscript.org/install | bash ``` ```bash $ curl https://yamlscript.org/install | VERSION=0.2.19 bash ``` ```bash $ curl https://yamlscript.org/install | VERSION=0.2.19 LIB=1 bash ``` ```bash $ curl https://yamlscript.org/install | PREFIX=/tmp/yamlscript bash ``` -------------------------------- ### Multiple Documents in a YAML Stream Source: https://yamlscript.org/doc/yaml Demonstrates how to start a new document within the same stream using '---'. This example includes an anchor and a tag for the top-level sequence. ```yaml --- &my-seq-1 !a-tag # The first sequence item is a scalar string with content of "first item". - first item # The second item is another sequence: - - one - two # It is possible, typical and preferred to collapse this like so: - - one - two # The third item is a mapping: - foo: bar baz: 42 # This may also be collapsed (and is also preferred) like so: - foo: bar baz: 42 # This sequence collapsing can be many levels deep: - - - - foo: bar ``` -------------------------------- ### Shorter Install Script for ys Source: https://yamlscript.org/doc/install A more concise command to install the 'ys' binary using a script from getys.org. Standard installation options can still be used. ```bash $ curl -sL getys.org/ys | bash ``` -------------------------------- ### Python YAMLScript Loading Example Source: https://yamlscript.org/doc/bindings Demonstrates how to load and process a YS file using the Python YAMLScript library. Ensure the 'libys.so' shared library is installed. ```python from yamlscript import YAMLScript ys = YAMLScript() input = open('file.ys').read() data = ys.load(input) print(data) ``` -------------------------------- ### Install ys and libys from Source Source: https://yamlscript.org/doc/install Build and install 'ys' and 'libys' from source code. This process requires 'bash', 'git', 'make', and 'curl', with an additional 'libz-dev' package on Linux. ```bash make install ``` ```bash make install PREFIX=... ``` -------------------------------- ### Install `ys` Command-Line Tool Source: https://yamlscript.org/doc/query Installs the `ys` command-line tool using a curl script and bash. ```bash curl -s https://getys.org/ys | bash ``` -------------------------------- ### YS File Example Source: https://yamlscript.org/doc/bindings An example of a YS file demonstrating variable assignment, function calls, and string interpolation. The '!ys-0' tag enables YS capabilities. ```yaml !ys-0: :: # Set values to use in data name =: "World" other =: load("other.yaml") foo:: +[(6 * 7), inc(41), 43.--, (3 .. 9):sum] bar:: other.stuff:shuffle.take(3) baz:: "Hello, $name!" ``` -------------------------------- ### YS CLI Build Output Example Source: https://yamlscript.org/doc/ys Represents the output after the 'build' stage, showing a more detailed internal representation of the data structure. ```yaml {:xmap [ [ {:Sym defn} {:Sym main} nil ] [ {:Lst [ {:Vec [{:Sym name} {:Sym n}]} {:xmap [{:Sym greet} [{:Sym name} {:Sym n}]]} ] } {:Lst [ {:Vec [{:Sym name}]} {:Lst [{:Sym main} {:Sym name} {:Int 3}]} ]} {:Lst [{:Vec []} {:Lst [{:Sym main} {:Str "world"} {:Int 3}]}]} ] ] [ {:Sym defn} {:Sym greet} nil ] [ {:Lst [ {:Vec [{:Sym name} {:Sym times}]} {:xmap [ [ {:Sym each} {:Vec [{:Sym i} {:Lst [{:Sym rng} {:Int 1} {:Sym times}]}]} ] {:xmap [ {:Sym say} {:Lst [ {:Sym str} {:Sym i} {:Str ") Hello, "} {:Sym name} {:Str "!"}]}]} ] } ] } {:Lst [ {:Vec [{:Sym name}]} {:Lst [{:Sym greet} {:Sym name} {:Int 1}]}]} ] ]} ``` -------------------------------- ### Install YS Interpreter Source: https://yamlscript.org/doc/run-ys Run this command to install the YS interpreter using curl and bash. ```bash $ curl -s https://yamlscript.org/install-ys | bash ``` -------------------------------- ### Install ys and libys with Homebrew Source: https://yamlscript.org/doc/install Use Homebrew to install or upgrade the 'ys' compiler and the 'libys' shared library on macOS or Linux. ```bash brew trust yaml/yamlscript brew tap yaml/yamlscript brew install ys # Install ys first time brew upgrade yaml/yamlscript/ys # Install new ys version later brew install yaml/yamlscript/libys # Install libys first time brew upgrade yaml/yamlscript/libys # Install new libys version later ``` -------------------------------- ### Bare Mode Example Source: https://yamlscript.org/doc/modes Demonstrates bare mode where all content is treated as data, similar to standard YAML 1.2. No YS code execution is possible. ```bash $ ys --load <(echo ' foo: count: [red, green, blue]') {"foo":{"count":["red","green","blue"]}} ``` -------------------------------- ### YS CLI Compose Output Example Source: https://yamlscript.org/doc/ys Demonstrates the output after the 'compose' stage in the YS CLI. This stage typically structures the initial data. ```yaml {:+ "=VAL", :$ "$i) Hello, $name!"} {:+"-MAP"} {:+"-MAP"} {:+"-MAP"} {:+"-DOC"} ``` -------------------------------- ### YS CLI Construct Output Example Source: https://yamlscript.org/doc/ys Illustrates the output after the 'construct' stage, which typically builds the final data structure from intermediate representations. ```yaml {:Top [ {:Lst [{:Sym declare} {:Sym greet}]} {:Lst [ {:Sym defn} {:Sym main} nil {:Lst [ {:Vec [{:Sym name} {:Sym n}]} {:Lst [{:Sym greet} {:Sym name} {:Sym n}]} ] } {:Lst [ {:Vec [{:Sym name}]} {:Lst [{:Sym main} {:Sym name} {:Int 3}]}]} {:Lst [{:Vec []} {:Lst [{:Sym main} {:Str "world"} {:Int 3}]}]} ] } {:Lst [ {:Sym defn} {:Sym greet} nil {:Lst [ {:Vec [{:Sym name} {:Sym times}]} {:Lst [ {:Sym each} {:Vec [{:Sym i} {:Lst [{:Sym rng} {:Int 1} {:Sym times}]}]} {:Lst [ {:Sym say} {:Lst [ {:Sym str} {:Sym i} {:Str ") Hello, "} {:Sym name} {:Str "!"}]}]} ] } ] } {:Lst [ {:Vec [{:Sym name}]} {:Lst [{:Sym greet} {:Sym name} {:Int 1}]}]} ] } {:Lst [{:Sym +++} {:Lst [{:Sym apply} {:Sym main} {:Sym ARGS}]}]} ]} ``` -------------------------------- ### Dot-chain Expressions Examples Source: https://yamlscript.org/doc/vocab Presents various forms of dot-chain expressions, showing function application and shorthand notations. ```yamlscript fn2(fn1(val1 val2)) val1.fn1(val2).fn2() val1.fn1(val2):fn2 ``` -------------------------------- ### YS CLI Resolve Output Example Source: https://yamlscript.org/doc/ys Illustrates the output after the 'resolve' stage, which typically involves resolving references and expressions. ```yaml {:xmap [ {:defn "defn main(name='world' n=3)"} {:xmap [{:expr "greet"} {:expr "name n"}]} {:defn "defn greet(name, times=1)"} {:xmap [ {:expr "each [i (1 .. times)]"} {:xmap [{:expr "say"} {:xstr "$i) Hello, $name!"}]}]}]} ``` -------------------------------- ### Basic Dot Chaining Examples Source: https://yamlscript.org/doc/chain Demonstrates various ways to use the dot operator for accessing map elements, calling functions, and applying core functions. ```yamlscript x.5 # -> (nth x 5) x.abc # -> (get+ x 'abc) x.foo() # -> (foo x) x.foo(abc 123) # -> (foo x abc 123) x.foo(abc _ 123) # -> (foo abc x 123) x.foo(abc 123 _) # -> (foo abc 123 x) x.foo(_ _ _) # -> (foo x x x) x.? # -> (truey? x) x.! # -> (falsey? x) x.++ # -> (inc x) x.-- # -> (dec x) x.# # -> (count x) x.#? # -> (not (empty? x)) x.#! # -> (empty? x) x.#++ # -> (inc (count x)) x.#-- # -> (dec (count x)) x.@ # -> (deref x) x.> # -> (DBG x) ``` ```yamlscript x.abc.5.foo(22).#++ # -> (inc (count (foo (nth (get+ x 'abc) 5) 22))) ``` ```yamlscript x.>.abc.>.foo() # -> (foo (DBG (get+ (DBG x) 'abc))) ``` -------------------------------- ### Mapping Syntax Say Hello World Source: https://yamlscript.org/doc/syntax Uses a YAML block mapping for the 'say' function call. Compiles to the same Clojure code as the previous examples. ```yamlscript !ys-0 say: "Hello, world!" ``` -------------------------------- ### YAML Anchor and Alias Example Source: https://yamlscript.org/doc/yaml Demonstrates how to define an anchor (&anchor) for a mapping and reference it using an alias (*anchor) to reuse the same data structure within a YAML document. ```yaml first: &anchor a: mapping second: *anchor # Both values are the same mapping: {"a": "mapping"}. ``` -------------------------------- ### Define and Run a Main Function Source: https://yamlscript.org/doc/control Defines a 'main' function that is executed when the program runs. Command-line arguments are passed to 'main' after attempting to cast them to numbers. This example demonstrates a loop and printing output. ```yamlscript !ys-0 defn main(word='Hello!' times=3): each i (1 .. times): say: "$i) $word" ``` -------------------------------- ### S-expression Example Source: https://yamlscript.org/doc/vocab Demonstrates a basic S-expression for printing the result of a multiplication. ```yamlscript (println (* 6 7)) # => 42 ``` -------------------------------- ### Prefix Call Notation Examples Source: https://yamlscript.org/doc/yes Demonstrates calling functions using prefix notation, similar to other programming languages. The function name must be directly adjacent to the opening parenthesis. ```yamlscript a: b c ``` ```yamlscript a b: c ``` -------------------------------- ### YAML Data File Example Source: https://yamlscript.org/doc/bindings A standard YAML file used as an external data source for a YS file. ```yaml stuff: - ark - banana - cat - doll - electron - flan - golf ball ``` -------------------------------- ### YeS-expression Example Source: https://yamlscript.org/doc/vocab Shows a YeS-expression, which allows infix operators and function names before parentheses. ```yamlscript println(6 * 7) ``` -------------------------------- ### YS CLI Print Output Example Source: https://yamlscript.org/doc/ys Shows the final 'print' output of the YS CLI, which is a human-readable representation of the processed YAML. ```clojure "(declare greet)(defn main ([name n] (greet name n)) ([name] (main name 3))..." ``` ```clojure "(declare greet) (defn main ([name n] (greet name n)) ([name] (main name 3)) ([] (main "world" 3))) (defn greet ([name times] (each [i (rng 1 times)] (say (str i ") Hello, " name "!")))) ([name] (greet name 1))) (+++ (apply main ARGS))" ``` -------------------------------- ### YS For Loop Syntax Source: https://yamlscript.org/doc/yaml Shows an example of how collection keys in YAML can be used in YS for constructs like for loops, iterating over multiple sequences or mappings. ```yaml # The collection key does have a good use case in YS. # Consider this `for` loop: for a foo(), b bar(), c [1 2 3]: say: a + b + c ``` -------------------------------- ### Pair Expression Example Source: https://yamlscript.org/doc/vocab Illustrates a Pair expression where the function is on the left-hand side of a mapping pair. ```yamlscript println: 6 * 7 ``` -------------------------------- ### Running ROT13 YS Program with Bash (First Run) Source: https://yamlscript.org/doc/run-ys Execute the ROT13 YS program using 'bash'. The first run will download and install the YS interpreter. ```bash $ bash rot13.ys I Love YS Installing the YS CLI '/tmp/yamlscript-run-ys/bin/ys-0.2.19' now... Ctl-C to abort See https://yamlscript.org/doc/run-ys for more information. Installed /tmp/yamlscript-run-ys/bin/ys - version 0.2.19 -------------------------------------------------------------------------------- V Ybir LF ``` -------------------------------- ### Basic Clojure S-Expressions Source: https://yamlscript.org/doc/clojure Demonstrates fundamental Clojure S-expressions, including function calls with arguments and nested expressions. These examples illustrate the core Lisp syntax of a function followed by its arguments. ```clojure (+ 1 2 3) ; `+` is a function that adds its arguments (str "Hello " name "!") ; `str` is a function that concatenates its arguments (println (str "The answer is " (+ 2 3 7) "!")) ; Multiple nested expressions ``` -------------------------------- ### Query YAML File with `ys` Source: https://yamlscript.org/doc/query Example of querying a YAML file to extract specific keys based on a filter and taking the first 5 results, outputting as YAML. ```bash $ ys '.some.0.part:keys.filter(/^[aeiou]/).take(5)' file.yaml ``` -------------------------------- ### Original Clojure FizzBuzz Implementation Source: https://yamlscript.org/doc/clj-to-ys This is the starting Clojure code for the FizzBuzz problem. ```clojure (defn fizzbuzz [start finish] (map (fn [n] (cond (zero? (mod n 15)) "FizzBuzz" (zero? (mod n 3)) "Fizz" (zero? (mod n 5)) "Buzz" :else n)) (range start finish))) (doseq [x (fizzbuzz 1 101)] (println x)) ``` -------------------------------- ### Running ROT13 YS Program with YS Interpreter Source: https://yamlscript.org/doc/run-ys Execute the ROT13 YS program using the 'ys' command after it has been installed. ```bash $ ys rot13.ys I Love YS V Ybir LF ``` -------------------------------- ### Function Chaining Operator Example Source: https://yamlscript.org/doc/operators Demonstrates the function chaining operator '.' in YS, showing how it compiles to nested Clojure function calls. ```yamlscript a.b.3.c(d).e(f) ``` -------------------------------- ### YeS Expression Say Hello World Source: https://yamlscript.org/doc/syntax Demonstrates the YeS Expression syntax where the function name is outside the parentheses. Compiles to the same Clojure code as the basic example. ```yamlscript !ys-0 say("Hello, world!") ``` -------------------------------- ### Example YS Program for ROT13 Encoding Source: https://yamlscript.org/doc/run-ys A YS program that prints the ROT13 encoding of its arguments. It includes the self-installer shebang and defines the ROT13 logic. ```yamlscript #!/usr/bin/env ys-0 source <(curl '-s' 'https://yamlscript.org/run-ys') "$@" : alphabet =: set((\A .. \Z) + (\a .. \z)) rot13 =: cycle(alphabet).drop(13 * 2).zipmap(alphabet) defn main(*input): say: str/escape(input.join(' ') rot13) ``` -------------------------------- ### YAML Parsing Error with Block Sequences in Code Mode Source: https://yamlscript.org/doc/gotchas YAML block sequences (lines starting with '-') are disallowed in YS code mode. This example shows the error message received when attempting to use them. ```bash $ ys -e ' say: - 1 - 2 - 3' Error: Sequences (block and flow) not allowed in code mode ``` -------------------------------- ### Running YS TAP Tests with prove Source: https://yamlscript.org/doc/ys-taptest Demonstrates how to execute a YS TAP test file using the `prove` command. Shows the expected output for a successful test run. ```bash $ prove -v test-1.t test-1.t .. ok 1 - Test merge ok 2 - Count keys 1..2 ok All tests successful. Files=1, Tests=2, 0 wallclock secs ( 0.01 usr 0.00 sys + 0.01 cusr 0.00 csys = 0.02 CPU) Result: PASS ``` -------------------------------- ### Clojure Hello World Source: https://yamlscript.org/doc/clj-to-ys The basic 'Hello, World!' program in Clojure. ```clojure (println "Hello, World!") ``` -------------------------------- ### YS CLI Help Output Source: https://yamlscript.org/doc/ys Displays the available options and usage instructions for the `ys` command. Use this to understand the full range of functionalities. ```bash $ ys --help ys - The YS Command Line Tool - v0.2.19 Usage: ys [] [] Options: -e, --eval YSEXPR Evaluate a YS expression multiple -e values are joined by newline -l, --load Output the (compact) JSON of YS evaluation -f, --file FILE Explicitly indicate input file -c, --compile Compile YS to Clojure -b, --binary Compile to a native binary executable -p, --print Print the final evaluation result value -o, --output FILE Output file for --load, --compile or --binary -s, --stream Output all results from a multi-document stream -T, --to FORMAT Output format for --load: json, yaml, csv, tsv, edn -J, --json Output (pretty) JSON for --load -Y, --yaml Output YAML for --load -U, --unordered Mappings don't preserve key order (faster) -m, --mode MODE Add a mode tag: code, data, or bare (for -e) -C, --clojure Treat input as Clojure code -d Debug all compilation stages -D, --debug-stage STAGE Debug a specific compilation stage: parse, compose, resolve, build, transform, construct, print can be used multiple times -S, --stack-trace Print full stack trace for errors -x, --xtrace Print each expression before evaluation --install Install the libys shared library --upgrade Upgrade both ys and libys --version Print version and exit -h, --help Print this help and exit ``` -------------------------------- ### Execute Compiled Binary with Custom Argument Source: https://yamlscript.org/doc/binary Runs the compiled binary with a custom argument, demonstrating how to pass parameters to the executable. ```bash $ time ./hello Bob Hello, Bob! real 0m0.014s user 0m0.005s sys 0m0.010s ``` -------------------------------- ### Single-Quoted String Example Source: https://yamlscript.org/doc/syntax Similar to the previous mapping example, but uses a single-quoted string. YS supports both single and double-quoted strings, with double quotes offering variable interpolation and escaping. ```yamlscript !ys-0 say: 'Hello, world!' ``` -------------------------------- ### Date/Time Function Source: https://yamlscript.org/doc/ys-std Get the current date and time. ```APIDOC ## Date/Time functions * `now() → Instant` — Returns `java.time.Instant` object ``` -------------------------------- ### YS Program Shebang Line Source: https://yamlscript.org/doc/run-ys If a YS program starts with a shebang line, the '!ys-0' tag is optional. ```yamlscript #!/usr/bin/env ys-0 ``` -------------------------------- ### YS Program YAML Tag Source: https://yamlscript.org/doc/run-ys A YS program must start with a YAML tag like '!ys-0'. ```yamlscript !ys-0 ``` -------------------------------- ### Compile YS to Binary and Compilation Output Source: https://yamlscript.org/doc/binary Demonstrates the command to compile a YS file to a binary executable and shows the typical output during the compilation process, including timing and resource usage. ```bash $ time ys --compile --binary hello.ys * Compiling YS 'hello.ys' to 'hello' executable * Setting up build env '/tmp/tmp.W0u4SGljdY' * This may take a few minutes... [1/8] Initializing (3.1s @ 0.24GB) [2/8] Performing analysis (12.2s @ 0.64GB) [3/8] Building universe (1.8s @ 0.45GB) [4/8] Parsing methods (1.6s @ 0.46GB) [5/8] Inlining methods (1.4s @ 0.63GB) [6/8] Compiling methods (17.7s @ 0.43GB) [7/8] Laying out methods (1.0s @ 0.49GB) [8/8] Creating image (1.7s @ 0.54GB) * Compiled YS 'hello.ys' to 'hello' executable real 0m48.929s user 6m44.965s sys 0m5.095s ``` -------------------------------- ### Basic Say Hello World Source: https://yamlscript.org/doc/syntax A simple YS program to print 'Hello, world!'. Requires the '!ys-0' tag to compile to Clojure code. ```yamlscript !ys-0 (say "Hello, world!") ``` -------------------------------- ### Switching to Code Mode with '::' Shorthand Source: https://yamlscript.org/doc/modes Illustrates the '::' shorthand for switching to code mode when defining a mapping value, providing a cleaner syntax than the '!' tag. ```bash $ ys --load <(echo ' !ys-0: foo:: count:: [red, green, blue]') {"foo":3} ``` -------------------------------- ### Range Operator Example Source: https://yamlscript.org/doc/operators Illustrates the range operator '..' in YS, which creates sequences. It differs from Clojure's `range` function. ```yamlscript 1 .. 3 3 .. 1 ``` -------------------------------- ### Passing Operators as Arguments Source: https://yamlscript.org/doc/yes Demonstrates how to correctly pass an operator as an argument to a function using prefix call notation or block mapping pairs to avoid misinterpretation. ```yamlscript apply(+ numbers) ``` ```yamlscript apply +: numbers ``` -------------------------------- ### Idiomatic YS Hello World Source: https://yamlscript.org/doc/clj-to-ys Refactoring the 'Hello, World!' program to idiomatic YS using 'say' and single-quoted strings. ```yaml !ys-0 say: 'Hello, World!' ``` -------------------------------- ### Switching to Code Mode in a Sequence Source: https://yamlscript.org/doc/modes Demonstrates how to use the '!' tag to switch to code mode when an element within a sequence requires code execution. ```bash $ ys --load <(echo ' !ys-0: - ! count:: [red, green, blue]') [3] ``` -------------------------------- ### Execute Compiled Binary with Default Argument Source: https://yamlscript.org/doc/binary Runs the compiled binary with no arguments, using the default value for the 'name' parameter. ```bash $ time ./hello Hello, world! real 0m0.014s user 0m0.002s sys 0m0.013s ``` -------------------------------- ### Alternative Variable Assignment Syntax Source: https://yamlscript.org/doc/syntax Demonstrates alternative syntaxes for variable assignment, including multi-line scalar values and explicit YAML key syntax. ```yamlscript foo = : bar() + 17 ``` ```yamlscript ? foo = : bar() + 17 ``` -------------------------------- ### Specify YS Interpreter Version for Development Source: https://yamlscript.org/doc/run-ys Use the YS_VERSION environment variable to run a YS program with a specific interpreter version without permanent installation. ```bash $ YS_VERSION=0.2.19 bash my-program.ys arg1 arg2 ... ``` -------------------------------- ### YAMLScript Hello World Program Source: https://yamlscript.org/doc/binary A basic YAMLScript program with a `main` function that prints a greeting. This is the source code compiled into a binary. ```yamlscript !ys-0 defn main(name='world'): say: 'Hello, $name!' ``` -------------------------------- ### Nested Mappings and Sequences in YAML Source: https://yamlscript.org/doc/yaml Demonstrates how to nest mappings and sequences to arbitrary depths using indentation. Sequence items can be indented with a leading dash. ```yaml third-key: a: sub-mapping second: - a sequence - of values - a scalar - - sub-sequence - items - another: sub-mapping another sequence: - one - two ``` -------------------------------- ### YS Hello 2.0 with YAML Mappings Source: https://yamlscript.org/doc/clj-to-ys Refactoring the function calls in the YS program to use YAML mapping pairs. ```yaml !ys-0 =>: !clj | (defn hello ([name] (println (str "Hello, " name "!"))) ([] (hello "World"))) hello: hello: 'YS' ``` -------------------------------- ### YAML Parsing Error with Flow Sequences in Code Mode Source: https://yamlscript.org/doc/gotchas This example shows the error message when a YAML flow sequence is used directly in YS code mode. ```bash $ ys -e 'say: [1, 2, 3]' Error: Sequences (block and flow) not allowed in code mode ``` -------------------------------- ### Running ROT13 YS Program with Bash (Subsequent Run) Source: https://yamlscript.org/doc/run-ys Execute the ROT13 YS program using 'bash' again. Subsequent runs will use the already installed YS interpreter. ```bash $ bash rot13.ys I Love YS V Ybir LF ``` -------------------------------- ### YS Hello World with Directive Source: https://yamlscript.org/doc/clj-to-ys Adding the '!ys-0' directive to a .ys file enables code evaluation. ```yaml !ys-0 (println "Hello, World!") ``` -------------------------------- ### Basic Function Definition and Call Source: https://yamlscript.org/doc/syntax Defines a function 'greet' using YS syntax and then calls it. Indentation is used for nesting, mirroring YAML's structure. ```yamlscript defn greet(name): say: "Hello, $name!" greet: 'Bob' ``` ```clojure (defn greet [name] (say "Hello, " name "!")) (greet "Bob") ``` -------------------------------- ### Compile Idiomatic YS to Clojure Source: https://yamlscript.org/doc/clj-to-ys Compiling the idiomatic YS 'Hello, World!' back to Clojure shows the translation. ```bash $ ys -c program.ys (say "Hello, World!") ``` -------------------------------- ### YAML Directives Source: https://yamlscript.org/doc/yaml Shows the YAML and TAG directives. The YAML directive specifies the specification version, and the TAG directive provides a shorthand for tag URIs. Directives require '---' to start a new document. ```yaml %YAML 1.2 ``` ```yaml %TAG !ys! tag:yamlscript.org,2022: ``` ```yaml --- # YAML allows a mapping key to be any node, not just a scalar. # In other words it allows collections or even aliases to be used as keys. - &map1 a: value # Here it is obvious that the key is a mapping. - *map1 : 42 # Here we are using YAML's "explicit key" syntax (`?`) to specify the key. - ? [a, flow, sequence] : 42 # We can use `?` with block collections too. - ? a: block mapping: key : 43 # We can even use it for literals scalar keys. - ? |- a literal scalar key : 44 ``` -------------------------------- ### YAML Document Structure and Basic Syntax Source: https://yamlscript.org/doc/yaml Illustrates the basic structure of a YAML stream with multiple documents separated by '---', including comments, mapping key-value pairs, and sequence elements. It shows different scalar styles for keys and values. ```yaml # A line starting with `---` is used to begin a new document. # It is not required for the first document in a stream. # It is common to put any tag or anchor for the top level node on the same # line as the `---`. --- # Let's start with the common mapping and sequence nodes. # Mappings are a group of "pairs", each consisting of a "key" and a "value" # separated by a colon. # Sequences are a group of nodes where each one is prefixed by a dash. # Both the colon and the dash must be followed by a whitespace to be valid. # The top level node of this document is a mapping. # For the first pair we have a scalar key and a scalar value. # Notice how the key is single-quoted and the value is double-quoted. 'first-key': "first-value" # The second pair has another scalar key and scalar value. second-key: second value # Notice that both of them are unquoted. # Scalars of can be expressed with or without quotes. # This is very common in YAML and very important in YS. # The kind of quoting (or lack thereof) is called the scalar's "style" in YAML. # The different quoting styles have different encoding rules and different # semantics. # There are actually 5 distinct scalar styles in YAML: plain, single quoted, # double quoted, literal and folded. # We'll cover these styles in more detail in a second. # Mapping pair values can be any kind of YAML node. ``` -------------------------------- ### Chain Method Calls in YS Source: https://yamlscript.org/doc/cheat Illustrates chaining method calls in YS, including the use of special chain operators for common operations like dereferencing, getting the last element, counting, and boolean checks. ```yamlscript say: read('/usr/share/dict/words') .lines():shuffle.take(3).join(' | ') # => specialty | mutation's | Kisangani ``` -------------------------------- ### YS Expression Escapes for YAML Scalars Source: https://yamlscript.org/doc/cheat Shows how to use the '+' prefix to turn YS expressions into valid YAML plain scalars when they start with special characters or follow quoted strings. The '+' is removed by YS. ```yamlscript +[1 2 3]: .map(inc) # => [2 3 4] =>: + 'foo' + 'bar' # => 'foobar' ``` -------------------------------- ### Run YS File (Initial) Source: https://yamlscript.org/doc/clj-to-ys Running a .ys file that lacks the YS directive, resulting in no output. ```bash $ ys program.ys $ ``` -------------------------------- ### Compile YS to Binary with Short Options Source: https://yamlscript.org/doc/binary Uses short-form options (`-cbo`) for the compile, binary, and output commands. ```bash $ ys -cbo say-hi hello.ys * Compiling YS 'hello.ys' to 'say-hi' executable ... ``` -------------------------------- ### YS Program with Self-Installer Shebang Source: https://yamlscript.org/doc/run-ys Begin a YS program with these lines to enable immediate execution via Bash, which will download the YS interpreter on the first run. ```yamlscript #!/usr/bin/env ys-0 source <(curl '-s' 'https://yamlscript.org/run-ys') "$@" : ``` -------------------------------- ### Basic YS Execution Source: https://yamlscript.org/doc/intro This snippet demonstrates the basic execution of a YS command within a YAML file using the '!ys-0' tag. ```yaml !ys-0 say: "Welcome to YS!" ``` -------------------------------- ### File System Queries Source: https://yamlscript.org/doc/ys-fs These functions query the properties of a given path. They can accept a single path, a list of paths, or a single list of paths, returning results in the same format. ```APIDOC ## File System Queries These functions query the properties of a given path. They can accept a single path, a list of paths, or a single list of paths, returning results in the same format. ### `abs?(Path) → Bool` Checks if a path is absolute. ### `dir?(Path) → Bool` Checks if a path is a directory. ### `empty?(Path) → Bool` Checks if a path is empty (file or directory). ### `exec?(Path) → Bool` Checks if a path is executable. ### `exists?(Path) → Bool` Checks if a path exists. ### `file?(Path) → Bool` Checks if a path is a regular file. ### `link?(Path) → Bool` Checks if a path is a symbolic link. ### `read?(Path) → Bool` Checks if a path is readable. ### `rel?(Path) → Bool` Checks if a path is relative. ### `size?(Path) → Bool` Checks if a file is not empty. ### `write?(Path) → Bool` Checks if a path is writable. ``` -------------------------------- ### Looping with List Comprehensions in YS Source: https://yamlscript.org/doc/cheat Shows how to use `each`, `map`, and `reduce` for list comprehensions and iterative operations in YS. ```yamlscript each i (1 .. 3): say: i ``` ```yamlscript map inc: (1 .. 3) ``` ```yamlscript reduce (fn [acc num] acc + num) 0: (1 .. 3) ``` ```yamlscript reduce _ 0 (1 2 3): fn(acc num): acc + num ``` -------------------------------- ### Define Multi-Arity Functions in YS Source: https://yamlscript.org/doc/cheat Shows how to define YS functions with default arguments, variable arguments, ignored arguments, and multiple arities. ```yamlscript defn greet(name): say: "Hello, $name!" defn greet(name='world'): # Default argument defn foo(bar *baz): # Variable number of arguments defn foo(*): # Any number of arguments defn foo(_ x _): # Ignored arguments defn foo: # Multi-arity function (): 0 (x): x (x y): x + y ``` -------------------------------- ### Switching to Code Mode with '!' - Success Source: https://yamlscript.org/doc/modes Shows the correct way to switch to code mode for a mapping value using the '!' tag, allowing the 'count' function to be called on a sequence. ```bash $ ys --load <(echo ' !ys-0: foo: ! count: ! [red, green, blue]') {"foo":3} ``` -------------------------------- ### Execute YS Hello World Source: https://yamlscript.org/doc/clj-to-ys Executing a Clojure string directly as YS using the '-e' flag. ```bash $ ys -e '(println "Hello, World!")' Hello, World! ``` -------------------------------- ### Program Output with Arguments Source: https://yamlscript.org/doc/control Shows the output of the 'program.ys' script when run with default arguments and when provided with custom arguments. ```shell $ ys program.ys 1) Hello! 2) Hello! 3) Hello! ``` ```shell $ ys program.ys YS 2 1) YS 2) YS ``` -------------------------------- ### Initial YAMLScript Conversion (Top-Level Pairs) Source: https://yamlscript.org/doc/clj-to-ys First YAMLScript version where top-level expressions become mapping pairs. Function arguments are updated to use parentheses. ```yamlscript !ys-0 defn fizzbuzz(start finish): (map (fn [n] (cond (zero? (mod n 15)) "FizzBuzz" (zero? (mod n 3)) "Fizz" (zero? (mod n 5)) "Buzz" :else n)) (range start finish)) doseq [x (fizzbuzz 1 101)]: (println x) ``` -------------------------------- ### Collection Keys in YAML Source: https://yamlscript.org/doc/yaml Demonstrates using collections (mappings, sequences) as keys in YAML, including explicit key syntax ('?'). This is noted as a useful feature in YS for constructs like for loops. ```yaml - &map1 a: value # Here it is obvious that the key is a mapping. - *map1 : 42 # Here we are using YAML's "explicit key" syntax (`?`) to specify the key. - ? [a, flow, sequence] : 42 # We can use `?` with block collections too. - ? a: block mapping: key : 43 # We can even use it for literals scalar keys. - ? |- a literal scalar key : 44 ``` -------------------------------- ### Switching to Code Mode with '!' - Error Source: https://yamlscript.org/doc/modes Demonstrates an attempt to switch from data mode to code mode using '!' for a sequence, resulting in an error because sequences are not allowed in code mode. ```bash $ ys --load <(echo ' !ys-0: foo: ! count: [red, green, blue]') Error: Sequences (block and flow) not allowed in code mode ``` -------------------------------- ### Load YS File and Output YAML Source: https://yamlscript.org/doc/ys Executes a YS file and outputs the result as YAML. Use the `-lY` flags for loading and YAML output. ```bash ys -lY some.yaml num: 123 greet: Ciao, World! eat: cherry drink: Bar, Bar, Bar!!! ``` -------------------------------- ### Python Execution and Output Source: https://yamlscript.org/doc/bindings Shows the command to run the Python script and the expected output after processing the YS and YAML files. ```bash $ python prog.py {'foo': [42, 42, 42, 42], 'bar': ['cat', 'flan', 'doll'], 'baz': 'Hello, World!'} ``` -------------------------------- ### Convert YAML to Compact JSON and Pipe to `jq` Source: https://yamlscript.org/doc/query Converts a YAML file to compact JSON using `-l` and pipes the output to `jq` for further formatting. ```bash ys -l file.yaml | jq . # Pipe to jq for even prettier JSON output ``` -------------------------------- ### YS Program Definition Source: https://yamlscript.org/doc/ys A simple YS program defining a `main` function and a `greet` function. It demonstrates default arguments and iteration. ```yaml !ys-0 defn main(name='world' n=3): greet: name n defn greet(name, times=1): each [i (1 .. times)]: say: "$i) Hello, $name!" ``` -------------------------------- ### Infix Operator Notation Source: https://yamlscript.org/doc/yes Shows how to use infix operators in YeScript, translating to prefix notation. Parentheses are implied for simple operator triplets. ```yamlscript =>: a + b ``` ```yamlscript =>: a + b + c ``` ```yamlscript =>: (a + c) > c ``` -------------------------------- ### Command Line Usage for YAML Processing Source: https://yamlscript.org/doc/ys4yaml Shows how to use the `ys` command-line tool to process YAML files. The `-J` flag converts YAML to JSON, and `-Y` loads YAML with YS functional capabilities enabled. ```bash $ ys -J your-file.yaml ``` ```bash $ ys -Y file.yaml ``` ```bash $ ys -Y file.yaml ``` -------------------------------- ### File System Getters Source: https://yamlscript.org/doc/ys-fs Functions to retrieve specific information about a path, such as its absolute path, filename, or modification time. ```APIDOC ## File System Getters Functions to retrieve specific information about a path, such as its absolute path, filename, or modification time. ### `abs(Path) → Path` Get the absolute path. ### `basename(Path Ext?) → File` Get the file name of a path, without extension. ### `ctime(Path) → Int` Get the creation time of a file. ### `dirname(Path) → Dir` Get the directory name of a path. ### `filename(Path) → File` Get the file name of a path. ### `glob(Path) → [Path]` Glob a path. ### `ls(dir) → [File]` List a directory. ### `mtime(Path) → Int` Get the modification time of a file. ### `path(Path) → Path` Get the canonical path. ### `readlink(Path) → Path` Get the path of a symbolic link. ### `rel(Path) → Path` Get the relative path. ### `which(name) → Path` Find the path of an executable. ``` -------------------------------- ### YAMLScript with Chained Method Calls (Less Idiomatic) Source: https://yamlscript.org/doc/clj-to-ys Refactors the 'main' function body into a single chained expression. This is presented as less idiomatic but demonstrates chaining. ```yamlscript !ys-0 defn main(start=1 finish=100): each x (start .. finish): x.fizzbuzz().say() defn- fizzbuzz(n): cond: (n % 15).!: 'FizzBuzz' (n % 3).!: 'Fizz' (n % 5).!: 'Buzz' else: n ``` -------------------------------- ### External Library Function Source: https://yamlscript.org/doc/ys-std Function to load external library pods. ```APIDOC ## External library functions * `use-pod(pod-name version) → nil` — Load an external library pod ``` -------------------------------- ### Simple YS TAP Test File Source: https://yamlscript.org/doc/ys-taptest Defines a simple test file using YS TAP for testing YS code. Includes test cases for merging hashes and counting keys, along with a `done` assertion for the number of tests. ```yaml #!/usr/bin/env ys-0 require ys::taptest: test done hash1 =:: foo: one bar: two hash2 =:: bar: three test:: - name: Test merge code: hash1.merge(hash2) want: foo: one bar: three - name: Count keys code: hash1.keys().count() want: 2 done: 2 # Make sure we ran 2 tests ``` -------------------------------- ### Call Functions in YS Source: https://yamlscript.org/doc/cheat Demonstrates various ways to call functions in YS, including scalar and map pair variations. ```yamlscript greet() # Scalar call variations greet('Bob') (greet 'Bob') -'Bob'.greet() greet: # Map pair call variations greet: 'Bob' greet 'Bob': ``` -------------------------------- ### YAMLScript with Main Function and Private Helper Source: https://yamlscript.org/doc/clj-to-ys Defines a 'main' function for automatic execution and a private 'fizzbuzz' helper function. Default arguments are added to 'main'. ```yamlscript !ys-0 defn main(start=1 finish=100): each x (start .. finish): say: fizzbuzz: x defn- fizzbuzz(n): cond: (mod n 15).!: 'FizzBuzz' (mod n 3).!: 'Fizz' (mod n 5).!: 'Buzz' else: n ``` -------------------------------- ### Compile YS to Native Binary Source: https://yamlscript.org/doc/ys Compiles a YS program into a standalone native executable. Use the `-b` flag for binary compilation. This process can be time-consuming. ```bash $ time ys -b program.ys * Compiling YS 'program.ys' to 'program' executable * Setting up build env in '/tmp/tmp.xU8K3OPymt' * This may take a few minutes... [1/8] Initializing (2.8s @ 0.14GB) [2/8] Performing analysis (9.1s @ 0.33GB) [3/8] Building universe (1.2s @ 0.39GB) [4/8] Parsing methods (1.4s @ 0.41GB) [5/8] Inlining methods (0.9s @ 0.49GB) [6/8] Compiling methods (10.6s @ 0.50GB) [7/8] Layouting methods (1.0s @ 0.50GB) [8/8] Creating image (1.5s @ 0.44GB) * Compiled YS 'program.ys' to 'program' executable real 0m36.340s user 4m34.165s sys 0m3.915s $ time ./program Bob 2 1) Hello, Bob! 2) Hello, Bob! real 0m0.007s user 0m0.003s sys 0m0.004s ```