Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

A gotcha when using Apple's blocks in (Objective-)C: what do you think this prints to the screen?

View HaskellClosureTest.hs
1 2 3 4 5 6 7 8
module HaskellClosureTest where
 
strings = ["do", "re", "mi"]
 
main = do
let printFunctions = map (\s -> putStrLn s) strings
-- prints "do, re, mi"
mapM_ id printFunctions
View HaskellClosureTest.hs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#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;
}
View HaskellClosureTest.hs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#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;
}
View HaskellClosureTest.hs
1 2 3 4 5 6 7 8 9 10 11 12 13
# 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.