@@ -61,6 +61,8 @@ start_link() ->
6161 {stop , Reason :: term ()} | ignore ).
6262init ([]) ->
6363 ets :new (feb_result , [set ,public , named_table ]),
64+ ets :new (input_count , [set ,public , named_table ]),
65+
6466 {ok , # state {}}.
6567
6668% %--------------------------------------------------------------------
@@ -78,10 +80,43 @@ init([]) ->
7880 {noreply , NewState :: # state {}, timeout () | hibernate } |
7981 {stop , Reason :: term (), Reply :: term (), NewState :: # state {}} |
8082 {stop , Reason :: term (), NewState :: # state {}}).
81- handle_call (Request , _From , State ) ->
82- Result = compute_fibonacci (Request ),
83+
84+ handle_call ({compute ,Input }, _From , State ) when is_list (Input ) ->
85+ case Input =:= lists :sort (Input ) of
86+ true ->
87+ Result = compute_fibonacci (Input ),
88+ lists :foreach (fun (Elem )->
89+ ets :insert (feb_result ,{Elem , Result }),
90+ ets :update_counter (input_count , Elem , {2 , 1 }, {Input , 0 })
91+ end ,
92+ Input ),
93+ {reply , Result , State };
94+ _ ->
95+ {reply , " Input list should be sorted one" , State }
96+ end ;
97+
98+ handle_call ({compute ,Input }, _From , State ) ->
99+ Result = compute_fibonacci (Input ),
100+ ets :update_counter (input_count , Input , {2 , 1 }, {Input , 0 }),
101+ ets :insert (feb_result ,{Input , Result }),
102+ {reply , Result , State };
103+
104+ handle_call (history , _From , State ) ->
105+ Count_List = ets :match_object (input_count , {'$0' , '$1' }),
106+ History =
107+ lists :map (fun ({Input ,_Count })->
108+ hd (ets :match_object (feb_result , {Input , '$1' }))
109+ end ,
110+ Count_List ),
111+
112+ {reply , History , State };
113+
114+ handle_call (count , _From , State ) ->
115+ Result = ets :match_object (input_count , {'$0' , '$1' }),
83116 {reply , Result , State }.
84117
118+
119+
85120% %--------------------------------------------------------------------
86121% % @private
87122% % @doc
@@ -147,6 +182,9 @@ code_change(_OldVsn, State, _Extra) ->
147182
148183compute_fibonacci (0 ) -> 0 ;
149184compute_fibonacci (1 ) -> 1 ;
185+ compute_fibonacci (N ) when is_list (N )->
186+ Res = [compute_fibonacci (X )||X <- lists :reverse (N )], % We always process higher element first to get more results to be cached
187+ lists :reverse (Res );
150188compute_fibonacci (N ) ->
151189 Num2 = case ets :lookup (feb_result ,N - 2 ) of
152190 [] ->
0 commit comments