If a variable containing a function gave the function's return instead of a reference to the function, what would an array of functions return? [closed]

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/229911

Question

I'm creating a prototype scripting language similar to something like Javascript. In my language, every single reference to a variable is actually a function call (a getter function), whether it has parentheses or not. So for example, if do this:

var foo = 3;
var bar = foo;

What really happens is foo.set() is called on the first line, which creates a new getter function. In the second line, the newly created getter function for foo is called, which looks like this:

foo.get()
{
    return 3;
}

I can also assign a function to a variable, in which case that function BECOMES the getter function.

var foo = 
{
    return 4+5;
}
var bar = foo; // bar is now equal to the number 9, NOT the function that foo contains

So what I'm working on now is what an array of functions should return. For example:

function func1
{
    return 1;
}
function func2
{
    return 2;
}

var foo = new array();
foo.push(func1);
foo.push(func2);

var bar = foo; //what does bar contain? [func1, func2] or [1, 2]?

A reference to a single function runs that function and gives the return of the function. So I'm trying to decide if a reference to an array of functions should also run those functions, or if it would be more advantageous to just return the array of functions.

In other words, would the getter function for foo look like this:

foo.get()
{
    return [func1.reference, func2.reference]; //would return [func1, func2]
}

Or like this:

foo.get()
{
    return [func1(), func2()]; //would return [1, 2]
}

Specifically, I'm asking if anyone knows if there are problems or solutions that one method or the other would create? Are there any established rules of good programming language design that apply here?

Was it helpful?

Solution

Use the first approach. Unless your language is pure functional, the second approach can have weird results. For example:

var x = 0;
function func
{
    return x;
}
var arr = new array();
arr.push(func);
var arr2 = arr;
x = 1;
print(arr[0]()); // prints "1"
print(arr2[0]()); // prints "0"

Or:

function func
{
    print("hello");
}
var arr = new array();
arr.push(func);
var arr2 = arr; // prints "hello"

PS: Are you sure you want to construct a new array every time you read an array variable?

Licensed under: CC-BY-SA with attribution
scroll top