|
1 | 1 | # Data Structures |
| 2 | + |
| 3 | +CN supports defining tagged union (also known as sum type or algebraic) data |
| 4 | +structures. |
| 5 | + |
| 6 | +!!! info |
| 7 | + TODO: Why define custom data structures? In the future, we'll extend this |
| 8 | + documentation to explain how to use CN data structures to verify the |
| 9 | + functional correctness of C algorithms. |
| 10 | + |
| 11 | +# Defining new data structure types |
| 12 | + |
| 13 | +The `datatype` keyword defines a new data structure type. It uses this syntax: |
| 14 | + |
| 15 | +```c |
| 16 | +/*@ |
| 17 | + datatype <name> { |
| 18 | + <constructor name> {<ctype> <field name>, ...}, |
| 19 | + ... |
| 20 | + } |
| 21 | +*@/ |
| 22 | +``` |
| 23 | +
|
| 24 | +For example, here's how to define a list of `int`: |
| 25 | +```c |
| 26 | +/*@ |
| 27 | + datatype int_list { |
| 28 | + Nil {}, |
| 29 | + Cons {i32 hd, datatype int_list tl} |
| 30 | + } |
| 31 | +*@/ |
| 32 | +``` |
| 33 | +
|
| 34 | +# Data structure operations |
| 35 | +
|
| 36 | +Once you've defined a new data structure, there are a few ways to use it. |
| 37 | +
|
| 38 | +## Creating new data structures |
| 39 | +
|
| 40 | +Create an instance of the data type by invoking its constructor. Using `int_list` as an example: |
| 41 | +```c |
| 42 | +/*@ |
| 43 | + // This is a list with a single node |
| 44 | + Cons {hd: 0i32, tl: Nil{}} |
| 45 | +@*/ |
| 46 | +``` |
| 47 | + |
| 48 | +## Matching values |
| 49 | + |
| 50 | +Unlike a C `union`, CN data structures are tagged with their constructor type. |
| 51 | +You can use the `match` keyword to break down an instance of the data struture |
| 52 | +and reason about each constructor individually. |
| 53 | + |
| 54 | +```c |
| 55 | +/*@ |
| 56 | + match my_int_list { |
| 57 | + // If the list is empty... |
| 58 | + Nil {} => { 0i32 } |
| 59 | +
|
| 60 | + // If the list has one element... |
| 61 | + Cons {hd : x1, tl: Nil{} } => { x1 } |
| 62 | +
|
| 63 | + // If the list has at least two elements... |
| 64 | + Cons {hd : x1, tl: Cons {hd: x2, tl: _ } } => { x1 } |
| 65 | + } |
| 66 | +@*/ |
| 67 | +``` |
0 commit comments