Search code examples
functional-programmingerlangvariable-assignmentdynamic-typing

How can Erlang support both single assignment and dynamic typing?


Let me start saying I am only a computer science enthusiast, with relatively little knowledge of the subject. My question is: if single assignment is the idea that a variable (e.g., A) can only be assigned a single value without that value to change (A = 1, A = 2 -> error) how can a language also have dynamic typing? If the value of a variable cannot change, surely it cannot change its type... right?


Solution

  • If a language is dynamically typed that means that it is not generally possible to determine the type of any given expression without running the program. That doesn't have to mean that variables have to be able to change their type, just that it's not possible to tell which type the variable has without running the program.

    So take this piece of code as an example:

    A =
        if some_condition -> 42;
        true -> "hello"
        end
    

    Here we can not know whether A is a number or a string without knowing whether the condition is true or false (which we can't generally know without running the code as it can be an arbitrarily complex expression). In a statically typed language the above would be illegal, but in Erlang it is allowed.