Skip to content

Instantly share code, notes, and snippets.

@dacap
Created March 22, 2012 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacap/2155047 to your computer and use it in GitHub Desktop.
Save dacap/2155047 to your computer and use it in GitHub Desktop.
More closure magic in pseudo-code
// Holly crap! Now we can give the "sum_and_count" function as a parameter.
FUNCTION Calculate_average ( sum_and_count, N1, N2, ..., NN )
LOCAL VARIABLE sum = 0
LOCAL VARIABLE count = 0
FOR_EACH N = N1, N2, ..., NN
CALL_THE_FOLLOWING_FUNCTION sum_and_count ( N )
RETURN num / count
END FUNCTION
// --------------------------------------------
// So the user can define its own sum_and_count
// function and pass it to Calculate_average
FUNCTION My_sum_and_count(x)
sum = sum + x // Oh, here we are referencing unbound variables,
count = count + 1 // but this is not a problem yet (inside Calculate_average they
// will be bound)
END LOCAL FUNCTION
// Here we pass "My_sum_and_count" function as a parameter to "Calculate_average"
// function. The interpreter will try to bound all unbound-variables when
// "Calculate_average" uses the "sum_and_count" function.
CALL_THE_FOLLOWING_FUNCTION Calculate_average ( My_sum_and_count, 8, 4, 6, 2, 7 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment