Mookayama
Mookayama

Reputation: 1343

Closure for simple use case

I do not understand the following practice interview question:

cons(a, b) constructs a pair, and car(pair) and cdr(pair) return 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.

What is the practical application of this?

Upvotes: 3

Views: 110

Answers (1)

Netwave
Netwave

Reputation: 42678

Cons is a function that takes 2 arguments and return a funtion that applies a function into a pair, so we can build up car and cdr in the same fasion:

def car(pair):
    def unpack(a, b):
        return a
    return pair(unpack)


def cdr(pair):
    def unpack(a, b):
        return b
    return pair(unpack)

This is an example/exercise that comes from functional programing, in where everything can be abstracted to functions (talking simply). It has real usage in with languages as Haskell or Racket for example. But I don't think it should be a real production ready option for python (IMO).

As you can see, there are no variables involved in the code others but the arguments themselves:

>>> car(cons(1, 2))
1
>>> cdr(cons(1, 2))
2

Upvotes: 1

Related Questions