Pair
Pair is a data structure which is used to combine two values.
(1, 4)
("sreedhar", "pavan")
Javascript does not provide this data structure. So let us implement this.
Represent pairs in JS
Pairs can be represented using an object
or an array
//Represent pair using object
function pair(a,b){
return {first: a, second: b};
}
function first(p){
return p.first;
}
function second(p){
return p.second;
}
//use the pair
const p = pair(12, 13)
const f = first(p)
console.log(f) // logs 12
const s = second(p)
console.log(s) // logs 13
//Represent pair using array.
function pair(a, b) {
return [a, b];
}
function first(p) {
return p[0];
}
function second(p) {
return p[1];
}
//use the pair
const p = pair(12, 13);
const f = first(p);
console.log(f); // logs 12
const s = second(p);
console.log(s); // logs 13
But is there a way to represent pair
in terms of functions
without using object
or array
?
Think for some time before you proceed.
.
.
.
Yes there is a way
Represent pair using functions
Consider our pair function returns a function.
function pair(a, b) {
return (value) => (value === 0 ? a : b);
}
Now this returned function when called with 0
returns the first element and when called with 1
returns the second element.
so we can implement first
and second
functions as
function first(p) {
return p(0);
}
function second(p) {
return p(1);
}
Finally with these functions we can represent pair using functions.
function pair(a, b) {
return (value) => (value === 0 ? a : b);
}
function first(p) {
return p(0);
}
function second(p) {
return p(1);
}
//use the pair
const p = pair(12, 13);
const f = first(p);
console.log(f); // logs 12
const s = second(p);
console.log(s); // logs 13
Conclusion
I would never implement pair using functions. But it was fun to realise that I can.
I found this in a section in SICP book.
Top comments (0)