Created
March 21, 2012 19:34
-
-
Save dacap/2151790 to your computer and use it in GitHub Desktop.
Pseudo-code to show closures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The following function, "Calculate_average", will be the only | |
// public function in your library API | |
FUNCTION Calculate_average ( N1, N2, ..., NN ) | |
LOCAL VARIABLE sum = 0 | |
LOCAL VARIABLE count = 0 | |
// Define a function named "sum_and_count" that isn't public API of your library, | |
// this function is visible and usable only inside "Calculate_average" | |
LOCAL FUNCTION sum_and_count(x) | |
sum = sum + x // The key of closures: here we can modify variables that are not in the scope of sum_and_count() | |
count = count + 1 | |
END LOCAL FUNCTION | |
// For each parameter of Calculate_average, we call "sum_and_count" with each element as parameter | |
FOR_EACH N = N1, N2, ..., NN | |
CALL_THE_FOLLOWING_FUNCTION sum_and_count ( N ) | |
// Wait a second, here we return "sum / count", but we didn't modify those | |
// variables... oh yeah, sum_and_count() has modified them (a closure: a | |
// subfunction that modified variables from other scope). | |
RETURN num / count | |
END FUNCTION |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment