2

I'm studying functional programming from here, and come across below code

const wasBornInCountry = person => person.birthCountry === OUR_COUNTRY
const wasNaturalized = person => Boolean(person.naturalizationDate)
const isOver18 = person => person.age >= 18

const isCitizen = person => wasBornInCountry(person) || wasNaturalized(person)

const isEligibleToVote = person => isOver18(person) && isCitizen(person)

Which can be shorten to below

const isCitizen = either(wasBornInCountry, wasNaturalized)
const isEligibleToVote = both(isOver18, isCitizen)

I can't seems to understand how

const isCitizen = person => wasBornInCountry(person) || wasNaturalized(person)

can be translated to below:

const isCitizen = either(wasBornInCountry, wasNaturalized)

How do we pass the parameter person into wasBornInCountry and wasNaturalized? What if I wish to call isCitizen with two parameters? How we know which parameter gonna be passed to wasBornInCountry and which parameter to wasNaturalized?

Isaac
  • 12,042
  • 16
  • 52
  • 116
  • @NicholasTower: Thank you very much for the pseudocode. It gives me a clearer picture! – Isaac Jan 29 '19 at 14:38
  • The point is that `either` and `both` are functions that each accepts two predicate functions are create a new predicate function out of them. You could write them as `both = (f1, f2) => arg => f1(arg) && f2(arg)` or `either = (f1, f2) => (...args) => f1(...args) || f2(...args)` depending up whether you need to supply multiple arguments or not. If you need more complicated scenarios where different arguments are passed to different functions, then `either` and `both` would not be enough. – Scott Sauyet Jan 29 '19 at 16:54
  • You might also [read about](https://en.wikipedia.org/wiki/Tacit_programming) [point-free style](https://stackoverflow.com/questions/944446/what-is-point-free-style-in-functional-programming). – Jared Smith Jan 29 '19 at 17:16

1 Answers1

4

How do we pass the parameter person into wasBornInCountry and wasNaturalized?

You don't. The function generated by either does.

What if I wish to call isCitizen with two parameters?

Then make sure that each of the two functions you pass to either accepts two parameters.

const same = (x, y) => x == y;
const ten = (x, y) => x == 10 || y == 10;
const f = R.either(same, ten);
console.log([f(1, 1), f(2, 1), f(10, 3)])

How we know which parameter gonna be passed to wasBornInCountry and which parameter to wasNaturalized?

Go and look at your original code:

const isCitizen = person => wasBornInCountry(person) || wasNaturalized(person)
  • The person parameter is passed to wasBornInCountry
  • The person parameter is passed to wasNaturalized

There is only one parameter. It is passed to both functions.

If there are multiple parameters, then they will all be passed to both functions.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335