zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[Functional Programming] Fst & Snd, Code interview question

ampcode Programming functional interview
2023-09-14 08:59:15 时间

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.

 

const Fst = P => {
  return P((a, _) => a);
};

const Snd = P => {
  return P((_, b) => b);
};

const Cons = (a, b) =>
  ((f) => f(a, b));

const res =  Fst(Cons(3,2));
console.log(res); // 3
const res1 = Snd(Cons(21, 22));
console.log(res1); // 22