1:
|
|
Legivel Tutorial
Yaml comes with a technical challenge; it supports structures which are
not suported in F# and C#. For example in Yaml you can create a list where each element is of a different type.
List<obj>
is seen as an undesired type - we wish static types, which are the main target for this library.
Legivel provides an F#-idiomatic Yaml to Native conversion. This simply means that it does not support all Yaml structures. This tutorial demonstrates all supported mappings. Note that prerequisite statements as #I/#r/open are left out of these examples.
Primitive mapping
Consider the folowing examples, which map a Yaml scalar to a primitive:
1: 2: 3: 4: 5: 6: 7: |
|
List mapping
In the examples below, an integer list is parsed. However you can use any supported type as list element.
1:
|
|
Which results in:
|
Yaml flow style:
1: 2: 3: 4: 5: |
|
Which results in:
|
Record mapping
In the example below, Yaml from example 2.4 is mapped to a record type. You can use attributes in the type definition, if the field name in Yaml is different than the record field name.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: |
|
Which results in:
|
Option mapping
In the example below, an option is parsed. When a value is available, it is mapped to Some(data). If the value is absent, it is mapped to None.
1: 2: 3: 4: 5: 6: 7: 8: |
|
Which results in:
|
Also "null" is translated to None:
1: 2: 3: |
|
Which results in:
|
Discriminated Union mapping
Discriminated unions can be compiled to a C# enum, or to an ordinary DU. They can also be appear as a value in Yaml (plain style), or one key/value pair in a mapping determines both Union Case and contained data (embedded style). You can also use an attribute to customize the yaml-to-union-case mapping.
Below an example of plain-style yaml which maps to a enum-DU:
1: 2: 3: 4: 5: 6: |
|
Which results in:
|
The following example demonstrates embedded style yaml which maps to a Union Case with record data:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: |
|
Which results in:
|
Map mapping
Yaml mapping Nodes can be converted to an FSharp Map type as follows:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: |
|
Which results in:
|
Map IDictionary
Yaml mapping nodes can be mapped to an IDictionary<'TKey,'TValue>, with the constraint that the target type has a parameterless constructor.
1:
|
|
Which results in:
|