Hello, my first post is here. I saw this tweet and decided to rewrite it to nim https://twitter.com/preslavrachev/status/1467555292242186241/photo/1
import strutils
var vertical_direction = 0
var horizontal_direction = 0
for line in "input.txt".readFile.splitlines:
let
line_parts = line.split " "
direction = line_parts[0]
magnitude = parseInt line_parts[1]
var sas: int = case direction # works
of "up": -magnitude
of "down": magnitude
else: 0
vertical_direction += case direction # ERROR expression expected
of "up": -magnitude
of "down": magnitude
else: 0
But I ran into a strangeness, the error expression expected, although according to the manual if and case are expressions.
So, is they are simply intended to be used with a variable declaration only?
import strutils
var vertical_direction = 0
var horizontal_direction = 0
for line in "input.txt".readFile.splitlines:
let
line_parts = line.split " "
direction = line_parts[0]
magnitude = parseInt line_parts[1]
var sas: int = case direction # works
of "up": -magnitude
of "down": magnitude
else: 0
vertical_direction += (case direction: # Works, probably due to parenthesis
of "up": -magnitude
of "down": magnitude
else: 0)
I guess it is due to conflicting operator precedence rules, with +=. IDK really though, new to Nim. (Glad to see you are a member of my Nim programming language Quora space!)I'm pretty sure it's because += is a regular infix operator just like div or mod but = isn't. ie. the following doesn't work
echo
if x == 2:
2
else:
-1
Basically, something is needed to "bind" the statement to the previous expression to tell the compiler it's an expression not a statement. So technically the following 2 things works
var x: int
`+=`(x):
if true:
1
else:
0
echo do:
if true:
1
else:
0