I've been writing code in python (interpreted language) for some time and as expected I, unconsciously, got habitual of writing interpreted code and python's lazy evaluation. For example, the following code works in python:
if(1 == 2):
print(a)
It doesn't matter if the variable a
has been declared or not, the code works because python never executes the print statement until the if
condition is true.
On the other hand, when you try to do it in a compiled language like nim, it fails, because as expected of a compiler, it evaluates everything it can during compilation. So I get the error:
if(1 == 2):
echo a #ERROR: undeclared identifier: 'a'
The above example seems extremely simple, but you can end up with this kind of gotcha anywhere, like I did when writing the following code in nim:
type
htag* = object
text: string
level: int
name: string
atag* = object
text: string
link: string
name: string
proc renderTag(tag: object): string =
echo tag
if(tag.name == "h"):
return "<h" & $tag.level & ">" & tag.text & "</h" & $tag.level & ">"
elif(tag.name == "a"):
return "<a href='" & tag.link & "' target='_blank'>"
else:
return "nothing"
Here, if I declare one kind of object, I'll get an undeclared field
error with the other.
Top comments (0)