Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DailyCodingProblems: f parameter/function

Tags:

python

So i'm working on the daily coding problems and the one i got today got me stumped.

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.

I don't understand what the "f" represents. I tried printing the thing i get from that function:

x = cons(3, 4)
<function cons.<locals>.pair at 0x2adc0ec45ae8>

But i still don't understand what it is. Any ideas?

like image 787
Yujin Kim Avatar asked May 15 '26 10:05

Yujin Kim


1 Answers

Let's examine cons:

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

So calling cons(3, 4) dynamically creates a function as if you statically define it like this :

def pair_3_4(f)
    return f(3, 4)

Similarly :

pair1 = cons(2, 6)
pair2 = cons(5, 8)
pair3 = cons("a", "b")

is equivalent to :

def pair1(f)
    return f(2, 6)
def pair2(f)
    return f(5, 8)
def pair3(f)
    return f("a", "b")

Now, let's examine pair:

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

From this, you can guess that f must be a callable object, and that it takes two arguments. The most simple callable object is a function, so let's say that f is a function.

Also you can see that pair simply calls f with whatever a and b were bound to it by cons.

Here is an example where I use print as the f :

>>> pair_3_4 = cons(3, 4)
>>> pair_3_4(print)
3 4
>>> cons(3, 4)(print)
3 4
>>> print(3, 4)
3 4
like image 170
sydpy Avatar answered May 16 '26 22:05

sydpy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!