Wednesday, October 14, 2009

Reading Notes #1

I have been reading Joe Armstrong's paper "Making reliable distributed systems in the presence of software errors" and making notes as I go. In chapter 3 the author gives examples of how Erlang handles higher order functions. One of them is a "generator" function.
  1. 1> Adder = fun(X) -> fun(Y) -> X + Y end end.  
  2. #Fun<erl_eval.5.123085357>  
  3. 2> Adder10 = Adder(10).  
  4. #Fun<erl_eval.5.123085357>  
  5. 3> Adder(10).  
  6. 15  

Line 1 defines an Adder that returns another function with X bound to the input to Adder. In line 2 we create a specific adder - in this case a function that adds 10 to its input. I think line 3 was meant to show how the specific adder created in line 2 could be invoked. If Adder10 were to be called with 5 as argument it would return 15. Instead Adder is invoked again and the result shown is not correct as Adder(10) would return a generator, not 15. I think the snippet can be modified thus:
  1. 1> Adder = fun(X) -> fun(Y) -> X + Y end end.  
  2. #Fun<erl_eval.6.49591080>  
  3. 2> Adder10 = Adder(10).  
  4. #Fun<erl_eval.6.49591080>  
  5. 3> Adder10(5).  
  6. 15