The functor seems pretty cool. The sad thing is, I still have the most
primitive implementation possible in my actual code. The reason is, I
don’t want to pop it in without fully understanding it.
The memo solution looks cleanest, that’s really just a gut feeling
though. Let me just make sure I get it. Here it is:
hashes.inject{|memo, hash| memo.merge(hash) {|k,e,v| e+ v}}
Now partly it turns out my problem is slightly more complicated. It’s
not an array of hashes; it’s an array of objects which can return
hashes. So it basically looks like this:
def enter_output
@items = get_the_items
@happy_output_hash = {}
non-destructively merge all hashes within @items into one hash
@items.each do |item|
item.hash_within.each do |key, value|
if @happy_output_hash[key]
@happy_output_hash[key] += value
else
@happy_output_hash[key] = value
end
end
end
end
(Code altered to enhance obviousness.)
Would the correct translation of the memo solution to accomodate this
be something like this?
items.inject{|happy_output_hash, item|
happy_output_hash.merge(item.hash_within) {|k,e,v| e + v}}
Also, what does the Functor solution actually do? That sounds Lispy,
which appeals to me, but I want to be sure the code is maintainable by
lesser mortals, such as, for example, me.
–
Giles B.
http://www.gilesgoatboy.org
http://giles.tumblr.com/