Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A gotcha when using Apple's blocks in (Objective-)C: what do you think this prints to the screen?
#include <Block.h>
#include <stdlib.h>
#include <stdio.h>
/* see <http://stackoverflow.com/questions/938429/scope-of-python-lambda-
functions-and-their-parameters> for for the inspiration for this */
/* block taking no parameters and returning void */
typedef void (^void_block_t)();
int main()
{
char* strings[3] = { "do", "re", "mi" };
void_block_t print_funcs[3];
int i;
for(i = 0; i < 3; i++)
{
char* s = strings[i];
/* note that the reason this works is not directly
* because of the block copy: it works because the
* Block_copy will perform a copy of s's current
* value when it copies the block, instead of simply
* referencing s. */
print_funcs[i] = Block_copy(^{ printf("%s\n", s); });
}
/* prints "mi, mi, mi" */
for(i = 0; i < 3; i++)
{
print_funcs[i]();
/* and don't forget to do this. yay memory management! */
Block_release(print_funcs[i]);
}
return 0;
}
#include <stdlib.h>
#include <stdio.h>
/* see <http://stackoverflow.com/questions/938429/scope-of-python-lambda-functions-and-their-parameters> for for the inspiration for this */
/* block taking no parameters and returning void */
typedef void (^void_block_t)();
int main()
{
char* strings[3] = { "do", "re", "mi" };
void_block_t print_funcs[3];
int i;
for(i = 0; i < 3; i++)
{
char* s = strings[i];
print_funcs[i] = ^{ printf("%s\n", s); };
}
/* prints "mi, mi, mi" */
for(i = 0; i < 3; i++)
{
print_funcs[i]();
}
return 0;
}
module HaskellClosureTest where
strings = ["do", "re", "mi"]
main = do
let printFunctions = map (\s -> putStrLn s) strings
-- prints "do, re, mi"
mapM_ id printFunctions
# stolen directly from <http://stackoverflow.com/q/938429>
def callback(msg):
print msg
#creating a list of function handles with an iterator
funcList=[]
for m in ('do', 're', 'mi'):
funcList.append(lambda: callback(m))
for f in funcList:
f()
#what do i print?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.