Eloquent Javascript: Higher Order Functions Example
Solution 1:
reduceAncestors(ph, sharedDNA, 0) / 4)
passes the sharedDNA
function as the second argument.
It gets assigned to f
here:
functionreduceAncestors(person, f, defaultValue)
f
gets called here:
f(person, valueFor(byName[person.mother]), valueFor(byName[person.father]));
… where you can see the second and third arguments which get assigned to fromMother
and fromFather
:
functionsharedDNA(person, fromMother, fromFather) {
Solution 2:
You could see it as follows:
First, f
and sharedDNA
are the same during the execution of this particular call.
Secondly, valueOf
can return the following values:
0, when
person == null
1, when
person == "Pauwels van Haverbeke"
(seeshareDNA
)Another value between 0 and 1 by the average of previously calculated values:
(fromMother + fromFather) / 2
So if "Pauwels van Haverbeke" is not found in the ancestry of "Philibert Haverbeke" then the final value will be 0.
But if "Pauwels van Haverbeke" is found as an immediate parent of "Philibert Haverbeke" then the final value, before division by 4 in the console.log
, is
(0 + 1) / 2 = 1/2
If "Pauwels van Haverbeke" is found as a grand-parent, then the final value is
((0 + 0) / 2 + (0 + 1) / 2) / 2 = 1/4
More generally, if he is found n generations back, the final value is
2 ^ (-n)
Now 2 ^ (-11) happens to be 0.0004882813..., so your (rounded) result 0.00049 means Pauwels van Haverbeke is an ancestor of Philibert Haverbeke, 9 generations earlier, taking into account that there is a division by 4 in console.log
.
Post a Comment for "Eloquent Javascript: Higher Order Functions Example"