Lambda in parameters

Julio Di Egidio julio at diegidio.name
Fri Dec 18 11:26:42 EST 2020


On Friday, 18 December 2020 at 15:20:59 UTC+1, Abdur-Rahmaan Janhangeer wrote:
> The Question: 
> 
> # --- 
> This problem was asked by Jane Street. 
> 
> 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. 
> # --- 

Notice that you don't need (Python) lambdas to code it, plain function definitions are fine:

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

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

pair = cons(1, 2)
assert car(pair) == 1
# ---

That said, few basic comments:  In Python, that 'cons' does not construct a pair, it rather returns a function with values a and b in its closure that, given some function, applies it to those values.  In fact, Python has tuples built-in, how to build them as well as how to access their members.  I take it the point of the exercise is how to use a purely functional language, such as here a fragment of Python, to encode (i.e. formalize) pairs and their operations.

Julio


More information about the Python-list mailing list