Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
-module(fruit_shop).
-export([spawn_shop/2, spawn_shop/3, buy/2, stock/1]).

buy( FruitShop, Order ) ->
  FruitShop ! { self(), buy, Order },
  receive
    { FruitShop, purchased, Price } -> {purchased, Price};
    { FruitShop, out_of_stock } -> out_of_stock
	after 10000 ->
		timeout
	end.

stock( FruitShop ) ->
	FruitShop ! { self(), stock },
	receive 
		{ FruitShop, stock, Stock } -> Stock
	after 10000 ->
		timeout
	end.

spawn_shop( Node, Stock, Prices ) -> 
	spawn( 
		Node,
		fun() ->
			fruit_shop_loop( Stock, Prices )
		end
	).

spawn_shop( Stock, Prices ) -> 
	spawn( 
		fun() ->
			fruit_shop_loop( Stock, Prices )
		end
	).

fruit_shop_loop( Stock, Prices ) ->
	receive
		{Buyer, stock} ->
			Buyer ! {self(), stock, Stock},
			fruit_shop_loop( Stock, Prices );
		{Buyer, buy, Order} ->
			{NewStock, Price} = buy( Order, Stock, Prices ),
			case Price of
				out_of_stock -> 
					Buyer ! {self(), out_of_stock},
					fruit_shop_loop( Stock, Prices );
				_ -> 
					Buyer ! {self(), purchased, Price},
					fruit_shop_loop( NewStock, Prices )
			end
	end.

buy( Order, Stock, Prices ) -> buy( Order, Stock, Prices, 0.0 ).

buy( [], Stock, _Prices, Acum ) ->
	{Stock, Acum};

buy( [{Kilos, Fruit} | Rest], Stock, Prices, Acum ) ->
	FruitStock = proplists:get_value(Fruit, Stock, 0.0),
	Stocked = Kilos =< FruitStock,
	case Stocked of
		true ->
			Price = proplists:get_value(Fruit, Prices),
			NewStock = [ {Fruit, FruitStock - Kilos}, proplists:delete(Fruit, Stock) ],
			buy( Rest, NewStock, Prices, Acum + (Price * Kilos));
		false -> {keep_old_stock, out_of_stock}
	end.