Created
February 27, 2012 22:35
-
-
Save teburd/1927622 to your computer and use it in GitHub Desktop.
Min Max Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(minmax). | |
-behaviour(gen_server). | |
-record(state, {range={undefined, undefined}}). | |
-export([test/0, start_link/0, range/0, stream/1]). | |
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, | |
terminate/2, code_change/3]). | |
test() -> | |
minmax:start_link(), | |
io:format("old range ~p ~n", [minmax:range()]), | |
minmax:stream(lists:map(fun (N) -> float(N) end, lists:seq(0, 10000))), | |
io:format("new range ~p ~n", [minmax:range()]). | |
start_link() -> | |
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). | |
range() -> | |
gen_server:call(?MODULE, range). | |
stream(Values) when is_list(Values) -> | |
gen_server:cast(?MODULE, Values). | |
init([]) -> | |
{ok, #state{}}. | |
handle_call(range, _, State=#state{range=Range}) -> | |
{reply, Range, State}. | |
handle_cast(Values, State=#state{range=Range}) when is_list(Values) -> | |
Range0 = minmax(Range, Values), | |
{noreply, State#state{range=Range0}}. | |
handle_info(_, State) -> | |
{noreply, State}. | |
terminate(_, _) -> | |
ok. | |
code_change(_, _, State) -> | |
{ok, State}. | |
minmax({undefined, undefined}, Values) -> | |
{lists:min(Values), lists:max(Values)}; | |
minmax({Min, Max}, Values) -> | |
{min(lists:min(Values), Min), max(lists:max(Values), Max)}. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment