Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spawning functions without exporting them

I am new to erlang and have a bit of a headache with the following scenario:

Take this code:

-module (so).
-export ( [foo/0] ).

bar () ->
    receive 
        die -> ok;
        Msg -> io:format ("I say ~p.~n", [Msg] )
    end.


bar (Name) ->
    receive 
        die -> ok;
        Msg -> io:format ("~s says ~p.~n", [Name, Msg] )
    end.

foo () ->
    Bar = spawn (fun bar/0),
    Bar ! "Hello",
    Bar ! die,
    Baz = spawn (?MODULE, bar, ["Alice"] ), % bar/1 not exported
    Baz ! "Hello",
    Baz ! die.

The process spawned with spawn/1 works fine, but the second process spawned with spawn/3 fails as expected because I haven't exported bar/1 and hence I get {undef,[{so,bar,["Alice"]}]}. Both spawn functions that take a parameter list (spawn/3 and spawn/4) also take a module name. But I don't want to export bar/1, because it is only used internally and never needs to be invoked from outside the module.

How can I spawn a function with arguments without exporting it?

like image 354
Hyperboreus Avatar asked Aug 02 '11 21:08

Hyperboreus


1 Answers

You can just put the call inside another fun like this:

spawn(fun() -> bar("alice") end)
like image 80
David Weldon Avatar answered Nov 19 '22 02:11

David Weldon