Function Pointers

I was writing something in python some days ago and I realised that python actually provides a neat way of handling function pointers. Or at least their version of it. Its called lambda.

>>> a = lambda x : x**x
>>> a(4)

So that got me thinking! In how many languages could I redefine pointers to functions/methods dynamically. So I decided to try Ruby; and lo and behold, Ruby has a another unique way. It does so, by passing around blocks.

>> def name
>> puts "Start"
>> yield 1, 2 if block_given?
>> puts "End"
>> end
=> nil
>> name { |x,y| puts "#{x} - #{y}" }
1 - 2
=> nil

Nifty, isn’t it!

Then there is the ever beautiful C. Simple and elegant

float add(float a , float b){return a+b;}
float minus(float a, float b){return a-b;}
float diva(float a, float b){return a/b;}
float mult(float a,float b){return a*b;}

float answer(float a, float b, float (*func)(float,float)){
return func(a,b);

Call => answer(a, b, &add);

As you can see, only in see do we actually explicitly pass around the address of the function itself, which is why I like C so much, because simply by looking at the code, I know exactly what is happening.

Now looking at Cocoa, I can hardly see any major difference between that and C. Sure, you have a whole heap of square brackets strewn about and the letters “NS” pop up irritatingly everywhere but, it is still C, which makes it cool. Although, I still have to figure out why interactions between Obj-C code and Interface Builder seem to resemble static method calls.

Perl too fairly easily resembles C when it comes to passing around subroutine pointers.

Of course the grand daddy of all these is Lisp and Scheme and you can not do much in them unless you deal in functions. Other languages I want to mess about in with regards to function pointers is Scala and Dylan.

This was heaps of fun 😀

Categories: /


About “Mujtaba Hussain”

I have no idea what to write here :(