Erlang/OTP Forums

Author Message

<  Erlang  ~  (newbie) including 'unused' local functions

rlysens
Posted: Tue Oct 02, 2007 8:13 pm Reply with quote
Joined: 02 Oct 2007 Posts: 1 Location: Belgium
Hi all,

Below is a variant of the clock example from the 'Programming Erlang' book. It's using the MFA version of spawn.
To get it to work I had to export tick/2. If I don't, I get this:

2> clock:start(1000,io:format("Tick~n") end).
** 1: syntax error before: 'end' **
2> clock:start(1000,fun() -> io:format("Tick~n") end).
true

=ERROR REPORT==== 2-Oct-2007::22:02:58 ===
Error in process <0.40.0> with exit value: {undef,[{clock,tick, [1000,#Fun<erl_eval.20.62269157>]}]}

Exporting tick/2 is probably not the right solution. Can anybody tell me what is the correct approach?

Thanks,

Ruben.


Code:

-module(clock).
-export([start/2, tick/2, stop/0]).

stop() -> clock ! stop.

tick(Time, Fun) ->
    receive
   stop ->
       void
    after Time ->
       Fun(),
       tick(Time, Fun)
    end.

start(Time, Fun) ->
    Pid = spawn(clock, tick, [Time, Fun]),
    register(clock, Pid).
View user's profile Send private message
hao
Posted: Fri Oct 12, 2007 8:59 am Reply with quote
User Joined: 20 Aug 2007 Posts: 18 Location: Uppsala, Sweden
Hi, rlysens,

I have tried your code on the Erlang shell. Here is an alternative solution I have figured out.

Code:

-module(clock).
-export([start/2, stop/0]).

stop() -> clock ! stop.

tick(Time, Fun) ->
    receive
        stop ->
            void
    after Time ->
            Fun(),
            tick(Time, Fun)
    end.

start(Time, Fun) ->
    F = fun() -> tick(Time, Fun) end,
    Pid = spawn(F),
    register(clock, Pid). 


I hope this will be helpful. It works well without exporting tick/2 function. I think function variable/object in Erlang is quite useful and/or powerful.
View user's profile Send private message Send e-mail MSN Messenger
francesco
Posted: Mon Oct 15, 2007 2:26 pm Reply with quote
User Joined: 07 Jul 2006 Posts: 249 Location: London
Hi rlysens,

You should export tick/2, as all functions in the spawn(M,F,A) BIF have to be exported, as it is "called" by a function outside the module. That is not the case with the spawn(fun()-> ... end), as local functions are encapsulated in the fun. So what you did is right.

Regards,
Francesco
--
http://www.erlang-consulting.com
View user's profile Send private message Visit poster's website

Display posts from previous:  

All times are GMT
Page 1 of 1
This forum is locked: you cannot post, reply to, or edit topics.

Jump to:  

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum