Eloquent Javascript: An Example of Higher Order Functions

  function reduceAncestors(person, f, defaultValue) {
    function valueFor(person) {
      if (person == null)
        return defaultValue;
      else
        return f(person, valueFor(byName[person.mother]),
                       valueFor(byName[person.father]));
  }
    return valueFor(person);
  }


  function sharedDNA(person, fromMother, fromFather) {
    if (person.name == "Pauwels van Haverbeke")
      return 1;
    else
      return (fromMother + fromFather) / 2;
  }
  var ph = byName["Philibert Haverbeke"];
  console.log(reduceAncestors(ph, sharedDNA, 0) / 4);
  // → 0.00049

I have many problems understanding this example from Eloquent Javascript. This is an example at the end of the chapter of functions of higher orders (chpt 5) under the heading "Great Great ..." I do not see where fromMother and fromFather get their values ​​from. I think they relate to valueFor (byName [person.mother] and valueFor (byName [person.father]), but I don’t see how or when the valueFor functions return the actual numeric value from the data (note that I obviously , didn’t include the data in this post, and I didn’t include the byName function.) Thank you in advance for any help!

+4
source share
2 answers

reduceAncestors(ph, sharedDNA, 0) / 4) sharedDNA .

f:

function reduceAncestors(person, f, defaultValue)

f :

f(person, valueFor(byName[person.mother]), valueFor(byName[person.father]));

... , fromMother fromFather:

function sharedDNA(person, fromMother, fromFather) {
+3

:

-, f sharedDNA .

-, valueOf :

  • 0, person == null

  • 1, person == "Pauwels van Haverbeke" (. shareDNA)

  • 0 1 : (fromMother + fromFather) / 2

, "Pauwels van Haverbeke" "Philibert Haverbeke", 0.

" " " ", , 4 console.log,

(0 + 1) / 2 = 1/2

"Pauwels van Haverbeke" ,

((0 + 0) / 2 + (0 + 1) / 2) / 2 = 1/4

, n ,

2 ^ (-n)

2 ^ (-11) 0.0004882813..., () 0.00049 , , 9 , , 4 console.log.

+2

All Articles