Background (which may be skipped, unless context is needed)
I've recently begun learning Mathematica (and only up to chapter 3 of Wellin), but wanted to write some code to get a better feel for syntax before reading on. I decided a good exercise would be to obtain a list of daily prices and volumes for a stock, i.e.
P = FinancialData["QCOM", All];
V = FinancialData["QCOM", "Volume", All];
These returned, respectively,
{{{1991,12,16},0.47},{{1991,12,17},0.46},{{1991,12,18},0.48},{{1991,12,19},0.46},{{1991,12,20},0.47},{{1991,12,23},0.47},<<5447>>,{{2013,8,16},66.9},{{2013,8,19},66.33},{{2013,8,20},66.71},{{2013,8,21},66.57},{{2013,8,22},67.13},{{2013,8,23},67.15}}
and
{{{1991,12,16},143667200},{{1991,12,17},16176000},{{1991,12,18},10899200},{{1991,12,19},7299200},{{1991,12,20},5235200},{{1991,12,23},7894400},<<5448>>,{{2013,8,19},9063600},{{2013,8,20},9064900},{{2013,8,21},8471500},{{2013,8,22},6694200},{{2013,8,23},8335800}}
Probably all the dates would line up, but for sake of learning, I wanted to intersect the two lists by date. That is, obtain a list like
{{{1991,12,16},{0.47,143667200}},{{1991,12,17},{0.46,16176000}}, ... }
Problem
The canonical answer for combining lists seemed to be How do I obtain an intersection of two or more list of lists conditioned on the first element of each sub-list?, answered in main by @Mr.Wizard.
But even after an hour of investigation, I cannot seem to wrap my mind around the following:
f1[a_List, b_List] :=
Reap[Sow[#2, #] & @@@ a ~Join~ b, a[[All, 1]] ⋂ b[[All, 1]], List][[2, All, 1]]
Here's where I've gotten:
a ~Join~ b
is using the infix form to join the price and volume lists.Sow[#2, #] &
is a "pure function" (which confuses me, because they seem more like "anonymous" functions, distinct from "pure [virtual] functions" in C++), swapping the first and second parameters.@@@
is shorthand forApply
-at-level-1, so in other words, it's executingSow[{1991,12,16}, 0.47]; Sow[{1991,12,17}, 0.46]; ...
for all the prices, and then all the volumes. The prices (and volumes) are what's being "sowed", and each sowing is "tagged" by the date.- The intersection,
a[[All, 1]] ⋂ b[[All, 1]]
, simply returns all the "keys" (dates) that are common between the two lists.
But, beyond that, I don't understand how Reap
brings it all together. Would someone explain the rest in simpler terms?
I'm a C++ developer, so I'm comfortable with programming terms. Either I'm not interpreting the documentation correctly, or my brain is fried from figuring out the rest.
Thanks very much in advance.
Reap
returns a list containing two things: the result of the expression passed to it, followed by a list containing the results of everySow
function call inside the expression. I think you're nearly there - if you're understanding Mr.Wizard's code so soon, you're winning! :) $\endgroup$