Created
June 28, 2020 00:06
-
-
Save exelotl/ef2507c58b4f81c74a197f99c56b9bd5 to your computer and use it in GitHub Desktop.
idea for a macro that lets you safely mutate some deep field access
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import macros | |
iterator mutIter[T](a: var T): var T = | |
yield a | |
macro mut(a, body: untyped) = | |
if a.kind != nnkInfix or a[0].strVal != "as": | |
error("Invalid first parameter to `mut`. Usage: `mut <expression> as <name>: <block>`", a) | |
let exp = a[1] | |
let name = a[2] | |
result = quote do: | |
for `name` in mutIter(`exp`): | |
`body` | |
echo repr(result) | |
when isMainModule: | |
type | |
Foo = object | |
points: array[5, Point] | |
Point = object | |
x, y: int | |
var foo: Foo | |
mut foo.points[3] as p: | |
p.x = 10 | |
p.y = 20 | |
echo foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment