I'm new to nim. I use the Option type in other languages and was playing around with them in nim (version 2.0.2):
{.experimental: "caseStmtMacros".}
import fusion/matching
let a =
case some(0)
of Some(_): 1
else: 2
echo a
let b =
case some(3)
of Some(_): 4
of None(): 5
echo b
I get a compile error for line 13 case some(3):
template/generic instantiation of case from here
and for line 14 of Some(_): 4:
Error: expression '4' is of type 'int literal(4)' and has to be used (or discarded)
I am trying to understand this. My guess is that since there is no else clause in the case some(3) statement, nim infers the type of this statement as the absence of any type. It then expects all branches of the case some(3) statement to have no type. So then nim complains that the 4 has to be discarded in order for the Some(_): branch to have no type.
The reason this example works is because both branches have assert statements that have no type.
So nim doesn't know that the Some(_) and None() branches form an exhaustive check of Option values? Is that a consequence of the Option type being implemented as a macro and not built into the language?
Thanks for reading!
So nim doesn't know that the Some(_) and None() branches form an exhaustive check of Option values?
Well it's cause the macro expands the case statement into if elif branches this can be seen in the following.
# compile with --expandMacro: case
{.experimental: "caseStmtMacros".}
import fusion/matching
let a =
case some(0)
of Some(_): 1
else: 2
echo a
let b =
case some(3)
of Some(_): discard 4
of None(): discard 5
echo b