DEV Community

Joseph Tully
Joseph Tully

Posted on

Function Decorators Problem in Python

I came across an interesting problem recently to do with a concept I was pretty unfamiliar with: function decorators. The problem came from the email subscription Daily Coding Problems. It stated:

cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.

Given this implementation of cons:

def cons(a, b):
    def pair(f):
        return f(a, b)
    return pair

Implement car and cdr.

Having some experience with Lisp languages (Scheme) I sort of got what was being asked: Implement these Lisp functions in python. But the stuff going on in the given code was weird to me, and actually there is a lot going on in these few lines of code. We have a function within a function, closure with the inner function accessing a and b although they aren't defined within it, and pair() taking in a function as an argument and cons() having a function as its return value. Also, what the heck is f?

After looking at the problem for a while I was still not getting it. I thought "cons is a function that returns a function which takes in a function and applies it to what was given as parameters to cons" which was too hard to wrap my head around. After looking up some stuff about function decorators, I had some better intuition and realized cons is modifying pair by telling it what to apply its parameter to. I then restated my analysis as "pair is a function that asks 'what should i do to a and b?' and cons is a function that makes pair functions for certain a's and b's". This made a lot more sense to me, and I was able to come up with the solution below:

def car (func):
    def retFirst(a,b):
        return a
    return func(retFirst)

This could be further reduced using lambda functions to my overall answer:

def car (f):
    return(f(lambda a,b: a))
def cdr (f):
    return(f(lambda a,b: b))

Just something I came across and found interesting, and maybe you will too! Also my first post on the site.

Top comments (0)