Skip to content

Instantly share code, notes, and snippets.

@forestbaker
Last active April 18, 2023 18:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save forestbaker/63960a80536dff501f2d to your computer and use it in GitHub Desktop.
Save forestbaker/63960a80536dff501f2d to your computer and use it in GitHub Desktop.
closure in bash ... ?
# closure - defined by Peter Landin in 1964
# closure - a function, plus a pointer to that functions scope
# In programming languages, closures (also lexical closures or function closures) are a technique for
# implementing lexically scoped name binding in languages with first-class functions. Duh.
# Operationally, a closure is a record storing a function[a] together with an environment:[1]
# A mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope)
# with the value or storage location to which the name was bound when the closure was created.
# A closure—unlike a plain function—allows the function to access those captured variables through the closure's reference to them,
# even when the function is invoked outside their scope.
# a closure may occur when a function is defined within another function,
# and the inner function refers to local variables of the outer function.
# Closures: In Bash, functions themselves are always global (have "file scope"), so no closures.
# Function definitions may be nested, but these are not closures, though they look very much the same.
# Functions are not "passable" (first-class), and there are no anonymous functions (lambdas).
# In fact, nothing is "passable", especially not arrays.
# Bash uses strictly call-by-value semantics (magic alias hack excepted).
####
# Example 1
####
declare -x OUTER_FUNC_RESULT=Outer_Function() {
local a=1
local inner_result=Inner_Function() {
alert(a)
}
return inner_result
}
fnc="$(OUTER_FUNC_RESULT)"
echo "$fnc"
####
# Example 2
####
var f, g;
function foo() {
var x;
f = function() { return ++x; };
g = function() { return --x; };
x = 1;
alert('inside foo, call to f(): ' + f()); // "2"
}
foo();
alert('call to g(): ' + g()); // "1"
alert('call to f(): ' + f()); // "2"
##########
@pinkeen
Copy link

pinkeen commented Jun 6, 2019

Nice, I've just accidentally came up with something like this:
https://gist.github.com/pinkeen/287ad64d951f7bf138afce975d3bce7b

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