user601836
user601836

Reputation: 3235

More info about spawning functions in Erlang

I have often seen people spawning new functions with arity 0 (no arguments) as:

 spawn_link(fun function_name/0).

where function_name/0 can be for example:

function_name() -> 
                   io:format("hello~n", []) 
end.

Can I spawn in a similar way a function which takes a parameter? For example:

function_name(Arg) ->
                   io:format("hello ~p ~n", [Arg])
end.

Should I use

spawn_link(Module, Function, Arg)

or something else?

Upvotes: 2

Views: 712

Answers (1)

Diego Sevilla
Diego Sevilla

Reputation: 29021

You can use that spawn_link with arguments, build a lambda function (fun) with the specified arguments or just with fixed ones. So for example you could use, as you say, just:

spawn_link(Module, Function, Args).

or export your own spawn_link (or start) in your module:

spawn_link(Args) ->
    spawn_link(?MODULE, fun myfun/X, Args).

or use a fun:

spawn_link(Args) ->
    spawn_link(fun () -> apply(fun myfun/X, Args) end).

or if you internally call some function with fixed parameters:

spawn_link() ->
    spawn_link(fun () -> myfun(1,2,3) end).

where X in this case is the arity of the myfun function in each case.

Upvotes: 6

Related Questions