loading...

Compiled VS Interpreted: A Code Example

sigmapie8 profile image Manav ・1 min read

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.

Posted on Feb 22 by:

sigmapie8 profile

Manav

@sigmapie8

- Freelance Developer/Trainer in Python. - Certified Ethical Hacker. - Python & Nim Enthusiast. - Email me for work: garg.manav8@protonmail.com

Discussion

markdown guide