{"path":"/sutl/guide/scope-and-reduce","content":{"title":"5. Scope and reduction","summary":"Local scope, conditionals, reduction and higher-order transforms.","body":"[sUTL](/sutl) · [Guide](/sutl/guide) · [Reference](/sutl/reference) · [Examples](/sutl/examples)\n\nThe source is immutable root input. Scope is the local environment used while\nevaluating a transform. At the top level they begin as the same value, but\nevaluate transforms and builtins extend scope with arguments.\n\nUse:\n\n- `$` for root source\n- `@` for caller scope\n- `^` as a selector for the current builtin scope\n\nMost ordinary transforms use `$` for input data and `@` for callback arguments.\n\n## Conditional scope\n\nThe `if` builtin evaluates only one branch after testing `cond`:\n\n```json\n{\n  \"&\": \"if\",\n  \"cond\": {\"'\": \"^@.enabled\"},\n  \"true\": {\"'\": \"enabled\"},\n  \"false\": {\"'\": \"disabled\"}\n}\n```\n\nQuoting protects the branch transforms from the dictionary's first evaluation\npass.\n\n## Iteration with `reduce`\n\nsUTL has no imperative loop. `reduce` evaluates a callback for each list item,\nadding these names to scope:\n\n- `item`: current list item\n- `accum`: previous accumulator\n- `ix`: zero-based item index\n\n```json\n{\n  \"&\": \"reduce\",\n  \"list\": [1, 2, 3, 4],\n  \"accum\": 0,\n  \"t\": {\"'\": [\"&+\", \"^@.accum\", \"^@.item\"]}\n}\n```\n\nResult: `10`.\n\n## Scope-name caution\n\nCompact builtins internally use `a` and `b` while folding arguments. Historical\nimplementations can therefore behave surprisingly when an enclosing scope also\nuses those names. Prefer descriptive scope names such as `item`, `value`,\n`left`, or domain-specific names in new transforms.\n\n## Higher-order transforms\n\nA callback is just another MLSNBN value. It can come from scope, source, or a\nlibrary and can be invoked using `!` or `!!`. This is how core transforms such\nas `map`, `filter`, and recursive algorithms are built without adding special\nsyntax.\n\nNext: [Declarations and libraries](/sutl/guide/declarations-and-libraries).\n\n## Continue learning\n\n[Previous: 4. Quoting and evaluation](/sutl/guide/quoting-and-evaluation) · [Guide contents](/sutl/guide) · [Language reference](/sutl/reference)\n\n## Source\n\nAdapted from [the sUTL source material](https://github.com/emlynoregan/sutllang-site/blob/e59ecafd364848cd71a1d18ce74cdf67f2f69328/content/guide/05-scope-and-reduce.md).\n\n[Back to sUTL](/sutl) · [Software & Agents](/topics/software-and-agents) · [All topics](/guide)","author":"Emlyn O'Regan"}}