views:

96

answers:

1

Is there a Mathematica function like inject in Ruby? For example, if I want the product of the elements in a list, in Ruby I can write:

list.inject(1) { |prod,el| prod * el }

I found I can just use Product in Mathematica:

Apply[Product, list]

However, this isn't general enough for me (like, if I don't just want the product or sum of the numbers). What's the closest equivalent to inject?

+6  A: 

The equivalent is Fold. I think this is more typically called "reduce" -- that's the Python name anyway.

Translating your example:

Fold[#1*#2&, 1, list]

That #1*#2& is a binary lambda function that multiplies its arguments. In this case you could just use Times instead:

Fold[Times, 1, list]

Or of course just apply Times to the list:

Apply[Times, list]

Or, for short:

Times @@ list

NOTE: The version in your question where you use Product instead of Times will not work. Product is for something else, namely the analog of Sum.

dreeves
Yeah, sorry, I was writing from memory and I meant to say `Times`.
Ben Alpert
'I think this is more typically called "reduce"'. I'd say the name fold is at least as common as reduce. The wikipedia page for the fold function lists 10 languages that call it fold and 8 that call it reduce. Also note that "Reduce (higher-order function)" redirects to "Fold (higher-order function)".
sepp2k