Loading ...
Sorry, an error occurred while loading the content.

Re: [netlogo-users] Looping through a list

Expand Messages
  • Jim Lyons
    ... Wowie zowie! I m so glad you posted this, Seth. I had given up on trying to use reduce to solve this problem, but had a feeling there must be a way. Once
    Message 1 of 4 , Aug 1, 2010
    • 0 Attachment
      On Jul 31, 2010, at 6:11 PM, Seth Tisue nonchalantly wrote in part:

      to-report partial-sums-functional [l]
      report butfirst reverse reduce [fput (first ?1 + ?2) ?1] fput [0] l
      end

      Wowie zowie! I'm so glad you posted this, Seth. I had given up on trying to use 'reduce' to solve this problem, but had a feeling there must be a way. Once again, by wielding the hidden powers of this mysterious and reclusive primitive reporter we are saved from plodding through some clunky loop to build up the list one element at a time. But how does it work? What is 'reduce' wearing under that shiny cape? It was a rewarding exercise to work through this one-liner to expose all that is going on, and it has helped me to understand 'reduce' better. So FWIW, and without further whimsy:

      The problem was to construct a list of the partial sums of a given list. As Marius originally asked, given a list [a b c ... n], create the list [a a+b a+b+c ... a+b+...+n].

      The first thing to understand about 'reduce' is that the special loop variable, ?1, is slightly different from the ?1 used in, say, 'sort-by'. In 'reduce', ?1 is the first element of the given list for the first iteration, but after that it is a kind of accumulator for the subsequent iterations. It holds the result of the calculation in the reporter block using the previous element, and ?2 is always the value of the next element.

      In the one-liner above, the list given to 'reduce' is actually the original list with a [0] prepended to it,

      [ [0]  a  b  c  ... n ]   -- starting 'work list'

      So now in the first iteration, the reporter block computes (first [0] + a), or 0+a, and then sticks this onto the front of ?1, giving

      [ [a 0]  b c ... n ]  -- 'work list' after one iteration

      In the next iteration, the reporter block computes (first [a 0] + b, or a+b, and puts it in front of the list it is building

      [ [a+b  a  0]  c ... n ]  -- 'work list' after two iterations

      The next iteration puts  a+b+c  onto the list, and so on. After the last iteration the result of 'reduce' is

      [ a+b+c+...+n ... a+b+c  a+b  a  0 ]

      To get the final list, this is reversed and then the extra element we added to get going is removed with butfirst

      [ a  a+b  a+b+c  ...  a+b+c+...+n ]

      Viola! Hope this helps someone.

      Jim
    Your message has been successfully submitted and would be delivered to recipients shortly.