数据抽象和过程抽象
April 2nd, 2010
越来越觉得erlang是个好工具,天生的符号抽象能力,几乎和scheme不相上下
- pow(D, N) ->
- pow_iter(normalize(D), D, N).
- pow_iter(R, _, 0) ->
- R;
- pow_iter(R, D, N) ->
- case N rem 2 of
- 1 ->
- pow_iter(mul(R, D), D, N - 1);
- 0 ->
- pow_iter(R, mul(D, D), N div 2)
- end.
- normalize([[_X11, _X12],[_X21, _X22]]) ->
- [[1,0],[0,1]];
- normalize([_X,_Y]) ->
- [1,1];
- normalize(_) ->
- 1.
- mul([[X11, X12],[X21, X22]],[[Y11,Y12],[Y21, Y22]]) ->
- [[X11 * Y11 + X12 * Y21, X11 * Y12 + X12 * Y22],
- [X21 * Y11 + X22 * Y21, X21 * Y12 + X22 * Y22]];
- mul([X1,Y1], [X2,Y2]) ->
- X1 * Y2 - X2 * Y1;
- mul(A, B) ->
- A * B.
- fib(N) when N > 0 ->
- [[F,_],[_,_]] = pow([[1,1],[1,0]], N - 1),F;
- fib(_) ->
- 0.
Recent Comments