Challenge Tuples
Julian Fondren
julian.fondren at gmail.com
Sat Apr 27 22:28:58 UTC 2024
On Friday, 26 April 2024 at 13:25:34 UTC, Salih Dincer wrote:
> You have a 5-item data tuples as Tuple(1, 2, 3, [1, 3], 5) and
> implement the sum (total = 15) with the least codes using the
> sum() function of the language you are coding...
Nim:
```nim
import std/[math, typetraits, macros]
macro unrollRange(low, high: static int; name, body: untyped) =
result = newStmtList()
for i in low ..< high:
result.add(newBlockStmt(newStmtList(
newConstStmt(name, newLit i),
copy body
)))
let t = (1, 2, 3, @[1, 3], 5)
var arr: seq[int]
unrollRange(0, t.tupleLen, i):
arr.add t[i]
doAssert arr.sum == 15
```
vs. D
1. there's no `each` on tuples
2. there's no static for loop, so a macro is needed for the tuple
indices
3. `add` is making use of the same overload as D's `~=`
More information about the Digitalmars-d-learn
mailing list