# Python basic example def test(): return 1 x = test() if x == 1: print(x) # With python 3.8 Walrus operator: def test(): return 1 if x := test(): print(x)
This code work with Perl
#!/usr/bin/perl sub test { return 1; } if ((my $x = test()) == 1) { print($x); }
I try the same with Nim, but not work
proc test(): int = return 1 proc main() = if (var x = test()) == 1: echo x main()
Simple and makes much more sense than Python's solution IMO:
proc test(): int =
return 1
proc main() =
if (var x = test(); x) == 1:
echo x
main()
template `:=`(a, b): untyped {.dirty.} =
let a = b
a
proc yes: bool = true
if x := yes():
echo x
is this the thing?template `:=`(a, b): untyped {.dirty.} = let a = b a proc yes: int = 1 if x := yes(): echo x
test.nim(7, 6) Error: type mismatch: got <int> but expected 'bool'
of course, nim doesn't implicitly converts ints to booleans.
... but if you really want, you can use converters.
... but if you really want, you can use converters.
... but if you can, you should avoid using int for bool
... but if you can, you should avoid using int for bool
... as it was—I thougth—clearly stated in the linked example: # bad style ahead: Nim is not C. as well in my post ("if you really want").
if (x := yes()) == y: # where y is the same type as returned by yes()
if (x := yes()) == y: # compares x to y
if x := yes() == y: # x is now bool as := takes two params: x and yes() == y