[Functional Programming] Fst & Snd, Code interview question
cons(a, b)
constructs a pair, andcar(pair)
andcdr(pair)
returns the first and last element of that pair. For example,car(cons(3, 4))
returns3
, andcdr(cons(3, 4))
returns4
.Given this implementation of cons:
def cons(a, b): def pair(f): return f(a, b) return pair
Implement
car
andcdr
.
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