No description
Find a file
Andy Davidoff edae1f2c5b editor config
2019-11-04 14:07:32 -05:00
.editorconfig editor config 2019-11-04 14:07:32 -05:00
foreach.nim error when trying to use open generics 2019-09-24 17:33:01 -04:00
foreach.nimble minor 2019-09-24 17:34:41 -04:00
LICENSE Initial commit 2019-09-21 14:59:59 -04:00
README.md clarify example 2019-10-31 00:13:32 -04:00

foreach

A sugary for loop macro with syntax for typechecking loop variables. I've found that this syntax is as helpful for documentation as it is for eliminating errors.

Example

import foreach

let a = [1, 2, 3]

foreach n in a.items of int:
  echo n, " is an int"

or

import json
import foreach

let j = %* {
  "one": 1,
  "two": "2",
}

foreach k, v in j.pairs of string and JsonNode:
	echo k, " is a string"
	echo v, " is a JsonNode"

but this will now fail at compile-time:

import json
import foreach

let j = %* {
  "one": 1,
  "two": "2",
}

# Error: loop variable `v` isn't a `string`
foreach k, v in j.pairs of string and string:
  echo k, " is a string"
  echo v, " is a string"

and you can use this to validate tuple field order/names:

import json
import foreach

type
  JsonKeyValue = tuple[key: string; value: JsonNode]

let j = %* {
  "one": 1,
  "two": "2",
}

# Error: loop variable `pair` isn't a `JsonKeyValue`
foreach pair in j.pairs of JsonKeyValue:
  assert pair.key is string

and for convenience, these compile to "normal" for loops:

import json
import foreach

let j = %* {
  "one": 1,
  "two": "2",
}

foreach k in 1 .. 5:
  assert k > 0

foreach k, v in j.pairs:
  echo k, " is a string"
  echo v, " isn't really a string"