i writing code reads 2 input files , checks if words in first file present in second file. want check elements of list 1 one via process message passing.
here code:
start()-> pid2 = spawn(?module,check2,[]), spawn(?module,check1,[pid2]). check1(pid2) -> {ok, data} = file:read_file("input.txt"), b = binary:split(data, [<<" ">>], [global]), k = [binary_to_list(item) || item <- b], [pid2 ! element || element <- k]. check2() -> {ok,iodevice} = file:open("check.txt", [read]), l = string:tokens(io:get_line(iodevice,""), "! ."), receive element -> case lists:member(element,l)of true -> io:format(element); false -> io:format("not_ok") end end.
the problem when want send element of list, sends first element. how can modify code send strings , check them?
the primary issue check2/0
function receives single element , exits. needs loop receive elements, , needs tell when stop. let's change functions 1 one below, starting start/0
:
start()-> pid2 = spawn(?module,check2,[]), check1(pid2).
the change here there's no need spawn check2/1
— can run directly start/0
.
next, here's our revised check1/1
function:
check1(pid2) -> {ok, data} = file:read_file("input.txt"), b = binary:split(data, [<<" ">>,<<"\n">>], [global,trim_all]), k = [binary_to_list(item) || item <- b], [pid2 ! element || element <- k++[stop]].
first, added newline split pattern, , trim_all
option rid of empty elements split. appended atom stop
list of elements send pid2
. let's @ our revised check2/0
function see why:
check2() -> {ok,iodevice} = file:open("check.txt", [read]), l = string:tokens(io:get_line(iodevice,""), "! .\n"), check2(l).
note we've split original check2/0
2 functions: check2/0
, check2/1
. because check2/1
function has recursive can receive elements sent it:
check2(l) -> receive stop -> ok; element -> case lists:member(element,l)of true -> io:format("found: ~s\n", [element]); false -> io:format("not found: ~s\n", [element]) end, check2(l) end.
notice inside receive
first check see if we've received atom stop
, , if do, exit function. otherwise, receive , check element
, , after call check2/1
recursively can receive either next element
or stop
atom.
Comments
Post a Comment