Home > Uncategorized > 数据抽象和过程抽象

数据抽象和过程抽象

April 2nd, 2010

越来越觉得erlang是个好工具,天生的符号抽象能力,几乎和scheme不相上下

  1. pow(D, N) ->
  2.         pow_iter(normalize(D), D, N).
  3.  
  4. pow_iter(R, _, 0) ->
  5.         R;
  6. pow_iter(R, D, N) ->
  7.         case N rem 2 of
  8.             1 ->
  9.                 pow_iter(mul(R, D), D, N - 1);
  10.             0 ->
  11.                 pow_iter(R, mul(D, D), N div 2)
  12.         end.
  1. normalize([[_X11, _X12],[_X21, _X22]]) ->
  2.         [[1,0],[0,1]];
  3. normalize([_X,_Y]) ->
  4.         [1,1];
  5. normalize(_) ->
  6.         1.
  1. mul([[X11, X12],[X21, X22]],[[Y11,Y12],[Y21, Y22]]) ->
  2.         [[X11 * Y11 + X12 * Y21, X11 * Y12 + X12 * Y22],
  3.          [X21 * Y11 + X22 * Y21, X21 * Y12 + X22 * Y22]];
  4. mul([X1,Y1], [X2,Y2]) ->
  5.         X1 * Y2 - X2 * Y1;
  6. mul(A, B) ->
  7.         A * B.
  1. fib(N) when N > 0 ->
  2.         [[F,_],[_,_]] = pow([[1,1],[1,0]], N - 1),F;
  3. fib(_) ->
  4.         0.

月影 Uncategorized

  1. No comments yet.