Archive for April, 2009

Erlang’s main strength is its support for concurrency– now I’ll extend the previous Erlang example to fetch the stock quotes for multiple symbols in parallel.

Because I love abstractions, I’ll use the function pmap– pmap works like map, but when the function is called it creates one parallel process to evaluate each argument in the list. You can find a copy of the code on the book’s website. Generally, it’s not advisable to use pmap when the the list is very small or very large. Ideally, the implementation of pmap should be modified to spawn n processes, but that is something that I’m not comfortable doing yet.

Full Listing

   1:  -module(quote).
   2:  -import(json_parser).
   3:   
   4:  -export([get_stock_quote/1, get_data_in_parallel/0]).
   5:   
   6:  -define(BASE_URL, "http://www.google.com/finance/info?client=ig&q=".
   7:   
   8:  symbols() ->
   9:      [ "MSFT", "RHIE", "INTC", "DPTR", 
  10:        "RVSB", "BBGI", "SRDD", "DEAR",
  11:        "ALKS", "GOOG", "QQQQ", "AAPL",
  12:        "RIMM", "GEOY", "CBST", "ANGO"
  13:      ].
  14:      
  15:      
  16:  get_google_url(Symbol) ->
  17:      ?BASE_URL ++ Symbol.
  18:     
  19:  get_stock_quote(Symbol) ->
  20:      %% moved inets:start() outside this function
  21:      URL =  get_google_url(Symbol),
  22:      { ok, {_Status, _Headers, Body }} = http:request(URL),
  23:      PureData = lists:subtract(lists:subtract(Body, "// [ "), "] "),
  24:      {_,{_,RealData},_} = json_parser:dvm_parser(list_to_binary(PureData)),
  25:      RealData.
  26:      
  27:   
  28:  get_data_in_parallel() ->
  29:      inets:start(),
  30:      lib_misc:pmap(fun get_stock_quote/1, symbols()).

Search