This repository has been archived by the owner. It is now read-only.

Aggregate Function Definition #24

Closed
rfratto opened this Issue Dec 27, 2015 · 0 comments

Comments

Projects
None yet
1 participant
@rfratto
Member

rfratto commented Dec 27, 2015

There are a few situations where you could have a series of functions that do the same thing with a minor variation. For example:

def add(var a, var b)
    printf("Calculating...\n")
    var result = a + b 
    printf("Result: %d\n", result)
    return result
end 

def subtract(var a, var b)
    printf("Calculating...\n")
    var result = a - b 
    printf("Result: %d\n", result)
    return result
end 

This code could be kept more DRY with the shared behavior abstracted into what I'm calling an "aggregate function definition":

aggregate def()
    printf("Calculating...\n")
    var result = 0

    def add(var a, var b)
        result = a + b 
        return result 
    end 

    def subtract(var a, var b)
        result = a - b 
        return result 
    end 

    printf("Result: %d\n", result) 
end

For functions in an aggregate definition, statements that appear before that function will be prepended to the statements of the function, executing first when the function is called. Statements that appear after the function will be executed on return.

If a $retval variable was supplied to represent the return value of the function, the example given above can be simplified even further:

aggregate def()
    printf("Calculating...\n")

    def add(var a, var b): return a + b 
    def subtract(var a, var b): return a - b 

    printf("Result: %d\n", $retval) 
end

$retval would not be read only, so a user could potentially change the return value at the last minute, for whatever reason they may have.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.