Tuesday 3 September 2013

Dynamo - List Processing

Many Dynamo layouts need to process lists. Lacing is one option, and recursion is another, but sometimes the built-in list-processing nodes Map, Reduce and Combine are just what you need.

Map applies a function to each element of a list and generates a list of the results. The function needs to have one unconnected input, and is called once for each element in the list: The element is fed into the unconnected input, and the function’s output is appended to Map’s output-list.

This is an example that doubles each element of a list:

image

You’d probably use Lacing for this in a real-world layout, but Map will work with custom nodes, whereas Lacing only works with Lacing-enabled built-in nodes at the moment. I’ll often create a custom node to ‘wrap’ a bunch of nodes, just to surface the single input that Map needs.

Combine is like Map, but takes two or more input lists. The number of unconnected inputs on the function needs to match the number of lists in the Combine. Just like Map, the output from Combine is a list of the outputs of the individual function calls.

And here’s an example using Combine to generate a series of Square numbers:

image

The same comment about Lacing applies…

In contrast to Map and Combine, Reduce just produces a single value, not a list. It’s inputs are a list, a function, and an initial value. The function needs to take one list element and the initial value, and output a single value. That value is then fed into the function along with the next element in the list. And the output from the Reduce node is the output from the last function-call.

As an example, here is Factorial implemented with Reduce:

image

Note that there’s nothing to stop you using a list as your ‘single input value’, so you can use Reduce to implement lots of other list-processing functions. And of course your function can inspect and edit the contents of the ‘single input value’ at each stage. Reduce is really very versatile.

Another example, generating a Fibonacci series using Reduce:

image

Which uses this Fibonacci custom node:

image

It’s a bit inelegant in places, but it does the job.

For the code-geeks, it does look as though the Reduce node in Dynamo is actually implemented as Fold in the underlying F#, so the name might change in future Dynamo releases.

No comments:

Post a Comment