# This works.
let t1 = if true: 1
else: 0
# This gets the error "Error: expression expected, but found 'keyword if'"
#let test = 0 + if true: 3
# else: 4
# This works.
let test = 0 + (block:
if true: 3
else: 4)
Is this intended? Is it a limit of the parser?
let test = 0 + (if true: 3
else: 4)
but got the error: "Error: expression expected, but found 'keyword else'"
Hmm. Ok - it was not your exact form. Sorry! All of these also work, though:
let test = 0 + (if true: 3 else: 4)
let test = 0 + (if
true: 3 else: 4)
let test = 0 + (if true:
3 else: 4)
let test = 0 + (if true: 3 else:
4)
let test = 0 + (if true: 3
else: 4)
but yeah, the one you list does not.
Maybe this is an undocumented (or even documented?) parser limitation or maybe it's a bug? I suspect it's some hard to resolve ambiguity in that exact case. The block workaround you found isn't so bad.
why does this produce Error: expression expected, but found 'keyword case' ?
import std/strutils
func score*(word: string): int =
for c in word:
result += case toUpperAscii(c)
of {'A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'}: 1
of {'D', 'G'}: 2
of {'B', 'C', 'M', 'P'}: 3
of {'F', 'H', 'V', 'W', 'Y'}: 4
of 'K': 5
of {'J', 'X'}: 8
of {'Q', 'Z'}: 10
else: 0
You need to use parentheses to turn the case statement into an expression:
import std/strutils
func score*(word: string): int =
for c in word:
result += (case toUpperAscii(c)
of {'A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'}: 1
of {'D', 'G'}: 2
of {'B', 'C', 'M', 'P'}: 3
of {'F', 'H', 'V', 'W', 'Y'}: 4
of 'K': 5
of {'J', 'X'}: 8
of {'Q', 'Z'}: 10
else: 0)
The grammar is not structured in a way that supports mixing operators (like +=) with case/if/block/try etc expressions, so this isn't really a bug as much as unimplemented/not supported.
As for the OP, the issue is that the if is unindented while else is. So stuff like this also works:
let test = 0 + (
if true: 3
else: 4)
Yes, but, nevertheless, in this case, you have to use parentheses. This is the same thing with an if expression:
proc p(b: bool) =
var x = if b: 3 else: 4 # Compile.
var y = 1 + if b: 3 else: 4 # Doesn’t compile.
var z = 1 + (if b: 3 else: 4) # Compile.
Maybe this is a bug, but I don’t think so. This is probably a parsing constraint.