前面写的有些乱,重新整理一下代码和文档
step 1:先考虑最简化情况,只有一只股票,并且不考虑股票数量,没有考虑挂单时间顺序,使用一个list存放买卖交易队列,只要买/卖的价格高于/低于当前任意一个交易挂单,即可成交。
step 1:先考虑最简化情况,只有一只股票,并且不考虑股票数量,没有考虑挂单时间顺序,使用一个list存放买卖交易队列,只要买/卖的价格高于/低于当前任意一个交易挂单,即可成交。
-module(stock1).
-export([start/0,buy/2,sell/2]).
start()->
register(stock,spawn(fun()->loop([])end)).
buy(Price,Name) ->
stock!{buy,self(),Price,Name},
receive
{Pid,Response,Sell}->
{Response,Sell}
end.
sell(Price,Name) ->
stock!{sell,self(),Price,Name},
receive
{Pid,Response,Buy}->
{Response,Buy}
end.
loop(L)->
receive
{buy,Pid,Price,Name}->
case lookupsell({Price,none},L) of
{Price,none}->
Pid!{self(),hangup,waiting},
L2=[{buy,Price,Name}|L],
loop(L2);
{Price1,Sell}->
Pid!{self(),ok,Sell},
L2=remove({sell,Price1,Sell},L),
loop(L2)
end;
{sell,Pid,Price,Name}->
case lookupbuy({Price,none},L) of
{Price,none}->
Pid!{self(),hangup,waiting},
L2=[{sell,Price,Name}|L],
loop(L2);
{Price1,Buy}->
Pid!{self(),ok,Buy},
L2=remove({buy,Price1,Buy},L),
loop(L2)
end
end.
lookupsell({Price,Buy},[{sell,Price1,Name}|T]) ->
if
Price>Price1 -> lookupsell({Price1,Name},T);
true->lookupsell({Price,Buy},T)
end;
lookupsell({Price,Buy},[{buy,_,_}|T])->lookupsell({Price,Buy},T);
lookupsell({Price,Buy},[])->{Price,Buy}.
lookupbuy({Price,Sell},[{buy,Price1,Name}|T]) ->
if
Price<Price1 -> lookupbuy({Price1,Name},T);
true->lookupbuy({Price,Sell},T)
end;
lookupbuy({Price,Sell},[{sell,_,_}|T])->lookupbuy({Price,Sell},T);
lookupbuy({Price,Sell},[])->{Price,Sell}.
remove(Trade,L)-> [X||X<-L,X/=Trade].