Skip to content

Instantly share code, notes, and snippets.

@kachayev
Created October 30, 2012 20:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kachayev/3982860 to your computer and use it in GitHub Desktop.
Save kachayev/3982860 to your computer and use it in GitHub Desktop.
Implement mapping data structure and "classes" using functions and lists
## Author: Alexey Kachayev
## Email: kachayev@gmail.com
## Talk: "Functional programming with Python", UA PyCon 2012
## URL: http://ua.pycon.org/static/talks/kachayev/index.html#/
###############################################
## Imitate dictionary functionality
###############################################
def dict_pair((key, value)):
return lambda k: value if k == key else None
def dict_new(*items):
return dict_update(dict_pair((None, None)), *items)
def dict_update(base, *updates):
def merge(l, r):
return lambda k: l(k) or r(k)
return reduce(merge, map(dict_pair, updates), base)
###############################################
## "Dictionary" examples
###############################################
me = dict_new(("name", "Alexey"), ("topic", "FP with Python"))
print "Me[name]:", me("name")
print "Me[topic]:", me("topic")
print "Me[nothing]:", me("nothing") # should print None
up = dict_update(me, ("position", "CTO"), ("company", "Kitapps"))
print "Up[name]:", up("name")
print "Up[position]:", up("position")
print "Up[company]:", up("company")
###############################################
## Imitate classes
###############################################
from functools import partial
def ask(self, question):
return "{name}, {q}?".format(name=self("name"), q=question)
def talk(self):
return "I'm starting {topic}".format(topic=self("topic"))
def cls(*methods):
def bind(self):
return lambda (name, method): (name, partial(method, self))
return lambda *attrs: dict_new(*(list(attrs) + map(bind(dict_new(*attrs)), methods)))
Speaker = cls(("ask", ask), ("talk", talk))
me = Speaker(("name", "Alexey"), ("topic", "FP with Python"))
print "Me.name:", me("name")
print "Me.topic:", me("topic")
print "Me.talk():", me("talk")()
print "Me.ask(WTF):", me("ask")("WTF")
###############################################
## Output
###############################################
# Me[name]: Alexey
# Me[topic]: FP with Python
# Me[nothing]: None
# Up[name]: Alexey
# Up[position]: CTO
# Up[company]: Kitapps
# Me.name: Alexey
# Me.topic: FP with Python
# Me.talk(): I'm starting FP with Python
# Me.ask(WTF): Alexey, WTF?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment