Is there a way to do the following? I thought I'd seen something like this before, but have been unable to replicate this sort of syntax.
import std/random
randomize()
template customIf(body: untyped) =
if rand(10) >= 5:
body
customIf:
echo "true condition"
else:
echo "false condition"
I have seen ugly ways of doing this with the body being wrapped in parens etc. but am hoping there's a way to do this in a readable manner.
You have to use do:
import std/random
randomize()
template customIf(body1, body2: untyped) =
if rand(10) >= 5:
body1
else:
body2
customIf:
echo "true condition"
do:
echo "false condition"
template customIf(body: untyped): untyped =
let condition {.inject.} = (rand(10) >= 5)
if condition:
body
template otherwise(body: untyped): untyped =
if not(condition):
body
customIf:
echo "true condition"
otherwise:
echo "false condition"
You can do this with a macro, yes. There have been ideas for a minor patch to implement it for templates as well.
import std/[random, macros]
randomize()
macro customIf(body, elseBranch: untyped) =
echo elseBranch.treeRepr
# Else
# StmtList
# Command
# Ident "echo"
# StrLit "false condition"
let cond = quote do: rand(10) >= 5
result = newTree(nnkIfStmt,
newTree(nnkElifBranch, cond, body),
elseBranch)
customIf:
echo "true condition"
else:
echo "false condition"
Somewhat documented in development version manual
We should do an "obscure feature" survey to see what we should document better.
Honestly, this would be great.
It is actually kind of possible even with templates with the do, although you can't use else:
import std/random
randomize()
template customIf(body, body2: typed) =
if rand(10) >= 5:
body
else:
body2
customIf:
echo "true condition"
do:
echo "false condition"