Wow, following Zach Kron’s very kind article over at Buildz, I guess I’d better get posting. Here’s a quick study using Reduce, one of the List Processing nodes I talked about last time. I’ve had a couple of comments suggesting that Reduce is a bit hard to understand, which implies I didn’t explain it very well. So here goes for a more detailed explanation. Or perhaps I should just stop while I’m behind.

There are lots of ways to find the maximum element in a list. This one uses Reduce.

Reduce takes a function, an initial value, and a list. In this case, my function is a custom node called Max, which returns the higher of two input numbers.

So I feed my list into Reduce, and set the initial value (the a input on the Reduce node) to the First value in the list. This way, I know that my final output will be a value from the list. (You might think you could just use zero as an initial value, but what would happen if all the items in the list were negative numbers?)

So Reduce takes the initial number (I tend to think of this as ‘the number it has in its hand’), and feeds it to Max alongside the first item from the list. Obviously, they’re both the same number, so Max outputs that number. Then Reduce takes that number and feeds it to Max alongside the second item in the list. And so on. At each stage, if the number from the list is higher than the number that Reduce has in its hand already, then Max gives that higher number to Reduce. And after Reduce has walked through all the items in the list, the number it has in its hand is the highest number in the list.

Does that make sense?

Here’s the definition of Max:

It’d be trivial to change this into a Min node that returned the smaller of the two numbers. Then you could plug that into Reduce to extract the Minimum value from a list.

So, Reduce steps through each item in a list and ‘has a value in its hand’. Your function needs to take those two values as inputs, and give an output value back to Reduce. The eventual output from Reduce is the output from the function when it’s invoked with the last item in the list and the value that Reduce has in its hand at that point.

Clear as mud.

This comment has been removed by the author.

ReplyDeleteNice David, thanks a lot! I could not figure out what Reduce did but I think I understand now. I still have a bit of a hard time understanding what the expected input of f(x,a)is, probably because I see the inputs of that custom node as "a" and "b" and am not seeing where "x" in f(x) comes into play. I need to stare at it some more 8)

ReplyDeleteawesome website blog keep it up the good work

ReplyDeleteRamzan Mubarak Images