IF you have been looking for a shorthand if statement here is some code
type
pair*[T] = (T,T)
template `|`*[A](a:A,b:A):pair[A] = (a,b)
template `?`*[T](cond:bool,res:pair[T]):untyped =
if cond:
res[0]
else:
res[1]
oh how to use it
var a = 0==1 ? 1|2 # == 2
var b = 0==0? 1|2 # == 1
#must give the same types for the result
oh how to use it
var a = 0==1 ? 1|2 # == 2
var b = 0==0? 1|2 # == 1
#must give the same types for the result
So basically the existing:
var a = if 0 == 1: 1 else: 2
var b = if 0 == 0: 1 else: 2
with a bit different syntax?
You realize this evaluates both statements regardless of the condition
Evaluated yes
with a bit different syntax?
YesOr better yet:
var a = [2, 1][int(0 == 1)]
I've played a bit with this and I have created a simple macro (as a part of my macro-learning process):
import macros
macro `?`(a: bool, body: untyped): untyped =
let
b = body[1]
c = body[2]
result = quote:
if `a`: `b` else: `c`
And here it is how you can use it:
proc a1(): int =
echo "a1"
return 1
proc a2(): int =
echo "a2"
return 2
let
a = 0 == 1 ? "wow" ! "nothing unusual"
b = (3 == 1 + 2) ? "yup" & ", this also works" ! "nope"
c = 'a' < 'b' ? 65+27 ! 42
d = 'a' > 'b' ? a1 ! a2
echo a
echo b
echo c
echo d()
Notice that I use !, but you can also use | or any other not used symbol (: is used, and you cannot use it)