soma.cell

For..In Loops

for..in iterates over List values.

Example 013 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 ForLoop has no face and no memory. Handlers: run (line 14).

Generated from soma describe on this file.

The source

013_for_in.cell

// ============================================================================
// 013 — For..In Loops
// ============================================================================
// for..in iterates over List values.
//
// Run:   soma run 013_for_in.cell run
// Expect:
//   Fruits: apple banana cherry
//   Sum of 1..5: 15
//   Names: Alice, Bob, Carol

cell ForLoop {

    on run() {
        // for..in iterates over a list
        let fruits = list("apple", "banana", "cherry")
        let output = ""
        for fruit in fruits {
            output = concat(output, concat(fruit, " "))
        }
        let trimmed = trim(output)
        print("Fruits: {trimmed}")

        // Summing a list of numbers
        let numbers = list(1, 2, 3, 4, 5)
        let sum = 0
        for n in numbers {
            sum = sum + n
        }
        print("Sum of 1..5: {sum}")

        // Building a comma-separated string
        let names = list("Alice", "Bob", "Carol")
        let result = ""
        let count = 0
        for name in names {
            if count > 0 {
                result = concat(result, ", ")
            }
            result = concat(result, name)
            count = count + 1
        }
        print("Names: {result}")

        return "done"
    }
}

What the toolchain says

$ soma check 013_for_in.cell
warning: `output` grows by concatenation inside a loop — each step copies the whole value, so the loop is quadratic (8 MB took 32 s, a list + join() 30 ms): push the pieces to a List and `join(parts, "")` once
  --> 013_for_in.cell:19:13
   |
19 |             output = concat(output, concat(fruit, " "))
   |             ^
✓ 1 warning(s), no errors.
$ soma run 013_for_in.cell run
Fruits: apple banana cherry
Sum of 1..5: 15
Names: Alice, Bob, Carol
done