Search code examples
loopssmalltalkpharo

Modifing a variable with itself + dictionary values / Pharo - Smalltalk


when I run this code below i get on Transcript the values that I initialized both puntaje and div (0.0 0.0) the loops aren't changing them. The dictionaries puntajePeliculas and contadorPuntajes have the data that I need I've checked beforehand

Any ideas of why it isn't updating the values in the loops?

puntajeDelDirector: director
  | auxiliarPelis puntaje aux div |
  aux := data.
  puntaje := 0.0.
  div := 0.0.
  auxiliarPelis := aux listaPeliculasPorDirector: director.
  auxiliarPelis do: [:each | puntaje := puntaje + [puntajePeliculas at: each] ]. 
  auxiliarPelis do: [:each | div := div + contadorPuntajes at: each].
  Transcript show: div; cr.
  Transcript show: puntaje; cr.
  puntaje := puntaje / div.
  Transcript show: puntaje; cr.
  ^puntaje.

Solution

  • To update puntaje change

    auxiliarPelis do: [:each | puntaje := puntaje + [puntajePeliculas at: each]].
    

    with

    auxiliarPelis do: [:each | puntaje := puntaje + (puntajePeliculas at: each)]. 
    

    In other words, use parenthesis and not squared brackets around puntajePeliculas at: each.

    To update div, instead of

    auxiliarPelis do: [:each | div := div + contadorPuntajes at: each]. 
    

    write

    auxiliarPelis do: [:each | div := div + (contadorPuntajes at: each)].
    

    Explanation:

    In the first iteration, [puntajePeliculas at: each] (with squared brackets) is a block object, not the puntaje of movie each. Blocks get evaluated when they receive the #value message.

    In the second, the precedence of + which is a binary message, is higher than the precedence of at:, which is a keyword message. Therefore the compiler will interpret it as:

    (div + contadorPuntajes) at: each
    

    which doesn't make sense.