Follow

#python #toyprogrammingchallenge Here is a problem that even though the answer seemed easy, I don't understand what it is supposed to be teaching, or what's going on. Anyone care to explain this problem to me? 

# 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

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

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

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

print cdr(cons(3,4))
print car(cons(3,4))

@Absinthe It's an implementation of a lisp style list, using nothing but closures? No more point in it, than any other random puzzle I guess. I think without the cons hint it would have been more interesting, just "Implement cons, car and cdr using only functions/closures".

@namark what are the inplications of "cons" "car" and "cdr"? What are these terms suggesting?

@Absinthe Ah, those come from lisp, and are fundamental functions for working with lists(the fundamental data structure of lisp). Lot of fundamental.
cons (many chained together) is used to construct the list, car to get the first element, cdr to get the rest of the list after the first. These operation are enough to implement any sort of operation on these lists(treating them as immutable).

@Absinthe I just realized you are asking for the meaning of the words themselves... I have no idea...

@Absinthe ancient abbreviations? and I was hoping they were some cool french words...

@namark @Absinthe

CONS = construct
CAR = Contents of Address Register
CDR = Contents of Decrement Register

Assembly language instructions for one of the first lisp interpreters. I don’t know which machine.
Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.