soma.cell

Flatten and Zip

flatten() merges nested lists; zip() pairs up two lists.

Example 025 of the basic Soma programs: a small, commented program that teaches one thing. Every output below was printed by soma 3.2.4 when this page was built.

How it is built

The cell FlattenZip has no face and no memory. Handlers: run (line 17).

Generated from soma describe on this file.

The source

025_flatten_zip.cell

// ============================================================================
// 025 — Flatten and Zip
// ============================================================================
// flatten() merges nested lists; zip() pairs up two lists.
//
// Run:   soma run 025_flatten_zip.cell run
// Expect:
//   nested: [[1, 2], [3, 4], [5, 6]]
//   flat: [1, 2, 3, 4, 5, 6]
//   zipped: [{"left": "a", "right": 1}, {"left": "b", "right": 2}, {"left": "c", "right": 3}]
//   a = 1
//   b = 2
//   c = 3

cell FlattenZip {

    on run() {
        // Nested list (list of lists)
        let nested = list(list(1, 2), list(3, 4), list(5, 6))
        print("nested: {nested}")

        // flatten() merges one level of nesting
        let flat = flatten(nested)
        print("flat: {flat}")

        // zip() pairs corresponding elements from two lists
        let keys = list("a", "b", "c")
        let vals = list(1, 2, 3)
        let zipped = zip(keys, vals)
        print("zipped: {zipped}")

        // Each zipped element has .left and .right
        for pair in zipped {
            print("{pair.left} = {pair.right}")
        }

        return "done"
    }
}

What the toolchain says

$ soma check 025_flatten_zip.cell
✓ All checks passed.
$ soma run 025_flatten_zip.cell run
nested: [[1, 2], [3, 4], [5, 6]]
flat: [1, 2, 3, 4, 5, 6]
zipped: [{"left": "a", "right": 1}, {"left": "b", "right": 2}, {"left": "c", "right": 3}]
a = 1
b = 2
c = 3
done