ok I see what it;s doing. Its first calculating this part:
(deviation|a)
to check how far the elements deviate from the mean and returns an
array of the differences.
Then what happens next is that the square| is invoked on the returned
array from above:
square|deviation_returned_array
So it squares the result set, which returns an array of the
deviation_returned_array squared. THen we invoke reduce passing
squared_deviation_returned_array enumerable to the sum proc, which
just totals the result set:
sum<=squared_deviation_returned_array
And then divide by (a.size-1) and take the square root of it.
So I guess the lesson here is not only do parentheses indicate
priority in evaluating an expression, but the expressions next to the
ones in parentheses are evaluated before starting to evaluate from
left to right.
On Dec 22, 10:10 am, John Merlino <stoici...-YDxpq3io04c@public.gmane.org>
wrote:> Here are two methods defined in the Proc class, designed to be used
> for functional programming:
>
> def apply(enum)
> enum.map &self
> end
> alias | apply
>
> def reduce(enum)
> enum.inject &self
> end
> alias <= reduce
>
> Here''s an application of them:
>
> sum = lambda {|x,y| x+y }
> mean = (sum<=a)/a.size
> deviation = lambda {|x| x-mean }
> square = lambda {|x| x*x }
> standardDeviation = Math.sqrt((sum<=square|(deviation|a))/(a.size-1))
>
> This excerpt is taken from "The Ruby Programming Language".
>
> Here''s the thing. In the last line of the above code it uses
> "sum<=square". That reduce method expects an enumerable as an
> argument. And instead it is being sent a lambda held in square
> variable. This should fail because the inject method does not exist on
> the lambda. It exists on arrays, and other enumerable types. So what
> am I missing here?
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.