Skip to content

Link loop #418

@bvssvni

Description

@bvssvni

For more information about the link type, see #227.

Dyon has a link loop that makes repeated patterns of code generation or templates easier and faster.

The link items inside loop body is evaluated directly as if it was inside a link { ... } block.

For example:

gen_struct(name, fields: [{}]) = link {
    "pub struct "name" {\n"link i {
    "    pub "fields[i].name": "fields[i].type",\n"
    }"}\n\n"
}

Void expressions, continue and break

You can put expressions that do not return a value inside a link loop, and also use continue and break like in other loops. This is useful for filtering:

fn main() {
    list := sift i 10 {i+1}
    x := link i {
        // The `else` case returns no value, but that is OK.
        if (list[i] > 2) && (list[i] <= 7) {continue}
        list[i]", "
    }
    // prints `1, 2, 8, 9, 10,`
    println(x)
}

The continue keyword skips the rest of the link items for the current iteration, but link items that already are evaluated will be inserted.

The break keyword skips the rest of the link items and exits the loop.

Here is an example where you print out a list without a trailing comma:

fn main() {
    list := sift i 10 {i+1}
    last := len(list)-1
    x := link i {list[i] if i == last {break} ", "}
    // prints `1, 2, 3, 4, 5, 6, 7, 8, 9, 10`
    println(x)
}

When using a link { ... } inside the body, you get all-or-nothing case. Notice how 10 disappeared compared to the last example:

fn main() {
    list := sift i 10 {i+1}
    last := len(list)-1
    x := link i {link {list[i] if i == last {break} ", "}}
    // prints `1, 2, 3, 4, 5, 6, 7, 8, 9, `
    println(x)
}

You can use packed loop notation with the link loop as if it was a flat loop. Here is an advanced example:

fn main() {
    n := 3
    list := sift i n, j n, k n {floor(random()*9)+1}
    last := n-1
    x := link {"["'out: link i, j, k {
        if (i != 0) && (j == 0) && (k == 0) {" "}
        list[i][j][k]
        if (i == last) &&
           (j == last) &&
           (k == last) {break 'out}
        else if (j == last) &&
                (k == last) {";\n"}
        else if (k == last) {", "}
        else {" "}
    }"]"}
    // prints something like:
    // ```
    // [1 6 7, 1 7 7, 6 1 3;
    //  8 1 7, 5 7 9, 7 1 9;
    //  8 6 1, 7 9 8, 8 7 9]
    // ```
    println(x)
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions