Explanation of python code

Need some help with python code, I subscribed to Daily Coding Problem platform, where they supply a coding question everyday. However, there seems to be some python code involved in the question. I am well versed with js and java. I would really appreciate, if someone could explain what this python code is doing, either in plain english or convert it into js/java.

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

We need to implement cdr and car function.
Please don’t provide implementation of car or cdr, just explain cons function in either plain english or java.

Thanks in advance,

let’s see

# create cons function, that accepts two parameters, a and b
   # inside cons:
      # create pair function that accepts one parameter, f (must be a function)
         # inside pair:
               # call f function with arguments a and b and return the output
         # end pair
      # return pair function
   # end cons

so, cons is a function that returns a function (let’s call it cons-output), cons-output is a functiont that accepts a function as parameter, and will call this function with the arguments you have given to cons

cons-output = cons(a, b)
# cons-output is a function, it accepts a function as argument
final-result = cons-output(func)
# final-result will have value of func(a, b)

I hope to have been clear enough. If not asks again.

1 Like

Hi @ilenia,
Thank you very much for the explanation, it makes sense,
Based on above I tried to write definition of cdr and car in python only, I only know rudimentary python and don’t use it quite often. So could you please verify these implementations as well.

def car(cons_output):
    f = lambda  x, y : x
    return cons_output(f)

and for cdr

def cdr(cons_ouptut):
    f = lambda x,y : y
    return cons_output(f) 

I have to say I have no idea, I have not studied python much

I probably would have done it more similar to how could be done in javascript

That’s fine, anyways thanks for the explanation :slight_smile:

I mean, if this is a function that returns one of the parameters I think you are done, I just don’t know that syntax