March 2014 update

This commit is contained in:
Ingy döt Net 2014-04-02 16:56:35 +00:00
parent 09687c4926
commit a25938f123
1846 changed files with 21876 additions and 5203 deletions

View file

@ -0,0 +1,20 @@
(setf (symbol-function '^) #'expt) ; Make ^ an alias for EXPT
(defun print-stack (token stack)
(format T "~a: ~{~a ~}~%" token (reverse stack)))
(defun rpn (tokens &key stack verbose )
(cond
((and (not tokens) (not stack)) 0)
((not tokens) (car stack))
(T
(let* ((current (car tokens))
(next-stack (if (numberp current)
(cons current stack)
(let* ((arg2 (car stack))
(arg1 (cadr stack))
(fun (car tokens)))
(cons (funcall fun arg1 arg2) (cddr stack))))))
(when verbose
(print-stack current next-stack))
(rpn (cdr tokens) :stack next-stack :verbose verbose)))))

View file

@ -0,0 +1,43 @@
-module(rpn).
-export([eval/1]).
parse(Expression) ->
parse(string:tokens(Expression," "),[]).
parse([],Expression) ->
lists:reverse(Expression);
parse(["+"|Xs],Expression) ->
parse(Xs,[fun erlang:'+'/2|Expression]);
parse(["-"|Xs],Expression) ->
parse(Xs,[fun erlang:'-'/2|Expression]);
parse(["*"|Xs],Expression) ->
parse(Xs,[fun erlang:'*'/2|Expression]);
parse(["/"|Xs],Expression) ->
parse(Xs,[fun erlang:'/'/2|Expression]);
parse(["^"|Xs],Expression) ->
parse(Xs,[fun math:pow/2|Expression]);
parse([X|Xs],Expression) ->
{N,_} = string:to_integer(X),
parse(Xs,[N|Expression]).
%% The expression should be entered as a string of numbers and
%% operators separated by spaces. No error handling is included if
%% another string format is used.
eval(Expression) ->
eval(parse(Expression),[]).
eval([],[N]) ->
N;
eval([N|Exp],Stack) when is_number(N) ->
NewStack = [N|Stack],
print(NewStack),
eval(Exp,NewStack);
eval([F|Exp],[X,Y|Stack]) ->
NewStack = [F(Y,X)|Stack],
print(NewStack),
eval(Exp,NewStack).
print(Stack) ->
lists:map(fun (X) when is_integer(X) -> io:format("~12.12b ",[X]);
(X) when is_float(X) -> io:format("~12f ",[X]) end, Stack),
io:format("~n").

View file

@ -0,0 +1,7 @@
rpn=: 3 :0
queue=. |.3 :'|.3 :y 0'::]each;: y
op=. 1 :'2 (u~/@:{.,}.)S:0 ,@]'
ops=. +op`(-op)`(*op)`(%op)`(^op)`(,&;)
choose=. ((;:'+-*/^')&i.@[)
,ops@.choose/queue
)

View file

@ -0,0 +1,2 @@
rpn '3 4 2 * 1 5 - 2 3 ^ ^ / +'
3.00012

View file

@ -0,0 +1,7 @@
rpnD=: 3 :0
queue=. |.3 :'|.3 :y 0'::]each;: y
op=. 1 :'2 (u~/@:{.,}.)S:0 ,@([smoutput)@]'
ops=. +op`(-op)`(*op)`(%op)`(^op)`(,&;)
choose=. ((;:'+-*/^')&i.@[)
,ops@.choose/queue
)

View file

@ -0,0 +1,10 @@
rpnD '3 4 2 * 1 5 - 2 3 ^ ^ / +'
┌─────┐
│2 4 3│
└─────┘
5 1 8 3
3 2 _4 8 3
8 _4 8 3
65536 8 3
0.00012207 3
3.00012