Passing functions
You can think of functions as a collection
of instructions stored as a variable. Different languages handle that differently, so let's just look at python for now.
>>> m = {'name':'Fredrick Anderson','ssn':'287-32-4492'}
>>> m
{'name': 'Fredrick Anderson', 'ssn': '287-32-4492'}
>>> def m():
... print('foo')
...
>>> m
<function m at 0x103e3eca0>
>>> m()
foo
>>> printfoo = m
>>> printfoo()
foo
>>> m()
foo
The variable `m` is no longer a dictionary containing Fred's ssn. Wow. I bet naming and namespacing could become really important, what do you think?
Anyway, if functions are variables, we can pass them to functions right? Of course we can.
>>> def blurse(somestring):
... out = ""
... for _ in range(len(somestring)):
... out += random.choice(somestring)
... return out
...
>>> blurse("Charles Wong")
'segresl enWn'
>>> def dopple(somestring):
... somestring += somestring
... return somestring
...
>>> # This next line only passes the result of a function, not the function itself.
>>> blurse(blurse(dopple(dopple(blurse('Charles Wong')))))
'CheWnCsCeerCesonCoConWshnWseWssenCensnossoCCohoo'
So let's really do it...
# heckablurse.py
import random
def heckablurse(curses, anger_level, name):
out = ""
out += random.choice(curses)(name)
anger_level -= 1
while anger_level > 0:
anger_level -= 1
out += random.choice(curses)(out)
return out
def blurse(somestring):
out = ""
for _ in range(len(somestring)):
out += random.choice(somestring)
return out
def dopple(somestring):
somestring += somestring
return somestring
print(heckablurse([blurse, dopple], 13, "Charles W Wong"))
% python heckablurse.py
'very long cursed output`