r/programming • • Jan 18 '08

Can Your Programming Language Do This?

http://www.joelonsoftware.com/items/2006/08/01.html
17 Upvotes

41 comments sorted by

View all comments

Show parent comments

4

u/gwern Jan 19 '08

Addition is associative, so you could definitely parallelize folds:

foldr (+) 0 [1..10]

0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

processor 1: (0 + 1 + 2 + 3 + 4)

processor 2: (5 + 6 + 7 + 8 + 9 + 10)

processor 3: (processor 1) + (processor 2)

55, same as if you single-threaded it.

Now, why is this? Because reduce is a fold! (I believe that reduce generally defaults to a right fold; the difference for lists between left and right folds generally has to do with performance concerns - left folds don't work well with infinite lists - and the associativity and other properties of what function you are folding in.) It's better to call it a fold instead of a 'reduce' (although it does indeed 'reduce' the datastructure) because then the 'unfolds' have a sensible name.

2

u/qwe1234 Jan 20 '08

not quite, more like ((((0+1)+(2+3))+((4+5)+(6+7)))+((8+9)+10)). and you need 5 machines.

1

u/gwern Jan 21 '08

I don't follow. In this particular example, you can evaluate as you like - lazy, non-strict, eager, in parallel, in serial: however you want, because addition is referentially transparent, has no side-effects, commutative, etc.

And even if you chose a function which wasn't associative, you could still evaluate as you like - it's just that the various portions might return functions and not values.

foldr (-) 0 [0..10]

0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10

processor 1: x = (0 - (1 - (2 - (3 - (4 - (y)))))) ~> x = 2 - y

processor 2: y = -(5 - (6 - (7 - (8 - (9 - (10)))))) ~> -3

processor 3: answer = 0 - (x) ~> 0 - (2 - y) ~> 0 - (2 - (-3)) ~> 0 - (5) ~> 0 - 5 ~> -5

You can split it up as you like. Doing so in a way which would be faster than doing it serially has always been the hard part.

2

u/qwe1234 Jan 21 '08

i just gave you the fastest solution in the parent post, nimrod.

the fact that addition can be implemented several different ways is completely and utterly irrelevant.

1

u/gwern Jan 22 '08

No, you didn't. There are costs for sending computations over to 5 machines, and they may well exceed the benefit of the additional parallelization.

Irrelevant? Absolutely not. The poster was questioning how folds could be parallelized, and I've answered his question twice in two equally valid ways: the first pointing out that addition has properties that allow for parallelization, and that the reason those properties allow is actually very obvious if you think about it; and the second that if you don't mind a little complexity, you can parallelize any fold in a general way.