shadowing - Process crashes on second message in Erlang -


i have simple car process implemented in erlang:

-module(cars). -compile(export_all).  -record(state, {count=1}).  make_car() ->   spawn_link(fun() -> car_proc(#state{}) end).  car_proc(s) ->     receive         {idle, x} ->             io:format("idling ~p second(s)~n", [x]),             timer:sleep(x*1000);         {move, {x,y}} ->             io:format("move; x=~p, y=~p~n", [x,y]);         {stop, reason} ->             x = s#state.count,             io:format("stopped count ~p because ~p~n", [x+1, reason])     end,     x = s#state.count,     car_proc(s#state{count=x+1}). 

i can make idle, if call idle twice in row, breaks:

59> c = cars:make_car(). <0.207.0> 60> c!{idle,1}.          idling 1 second(s) {idle,1} 61> c!{idle,1}.          idling 1 second(s) {idle,1} 62>  =error report==== 9-apr-2013::00:00:00 === error in process <0.207.0> exit value: {{badmatch,2},[{cars,car_proc,1,[{file,"cars.erl"},{line,20}]}]}  ** exception error: no match of right hand side value 2      in function  cars:car_proc/1 (cars.erl, line 20) 

why?

the error occurs on line 20, is

x = s#state.count 

it occurs because pattern matching fails. variable 'x' defined in line , it's value 1, because has been determined in receive block:

receive         {idle, x} -> 

in erlang value of variable can defined 1 time. when send message {idle, 1} first time x becomes 1 , default value of s#state.count 1. in case 'x' matches s#state.count. when send {idle, 1} second time x 1 , s#state.count 2 (i.e. x , s#state.count not equal). error in pattern matching. can use variable avoid problem. change 2 last lines

x = s#state.count, car_proc(s#state{count=x+1}). 

to

count = s#state.count, car_proc(s#state{count=count+1}). 

and happy!


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -