Search code examples
programming-languagesvariablesfunctiondataflow

Are there any programming languages where variables are really functions?


For example, I would write:

x = 2
y = x + 4
print(y)
x = 5
print(y)

And it would output:

6 (=2+4)
9 (=5+4)

Also, are there any cases where this could actually be useful?

Clarification: Yes, lambdas etc. solve this problem (they were how I arrived at this idea); I was wondering if there were specific languages where this was the default: no function or lambda keywords required or needed.


Solution

  • Haskell will meet you halfway, because essentially everything is a function, but variables are only bound once (meaning you cannot reassign x in the same scope).

    It's easy to consider y = x + 4 a variable assignment, but when you look at y = map (+4) [1..] (which means add 4 to every number in the infinite list from 1 upwards), what is y now? Is it an infinite list, or is it a function that returns an infinite list? (Hint: it's the second one.) In this case, treating variables as functions can be extremely beneficial, if not an absolute necessity, when taking advantage of laziness.

    Really, in Haskell, your definition of y is a function accepting no arguments and returning x+4, where x is also a function that takes no arguments, but returns the value 2.


    In any language with first order functions, it's trivial to assign anonymous functions to variables, but for most languages you'll have to add the parentheses to indicate a function call.

    Example Lua code:

    x = function() return 2 end
    y = function() return x() + 4 end
    print(y())
    x = function() return 5 end
    print(y())
    
    $ lua x.lua
    6
    9
    

    Or the same thing in Python (sticking with first-order functions, but we could have just used plain integers for x):

    x = lambda: 2
    
    y = lambda: x() + 4
    
    print(y())
    
    x = lambda: 5
    
    print(y())
    
    $ python x.py
    6
    9