[erlang-questions] Can Mnesia/ets/dets store functions?

Matthias Lang matthias@REDACTED
Sun May 24 09:27:07 CEST 2009

On Friday, May 22, Cameron Kerr wrote:
> I know Mnesia/ets/dets can store any arbitrary Erlang term, but does  
> this include funs? 


> Any complications with that?

One possible source of surprises is that funs created in modules are
part of the module, so the fun can change if the code does. Example:


  make_fun() ->
    fun() -> 66 end.

  1> c(ck).
  2> F = ck:make_fun(). 
  3> F().
  4> file:write_file("/tmp/fun_in_file", term_to_binary(F)).

And now terminate Erlang, edit 'ck' (for instance make the fun return
67) and start a new emulator:

  1> c(ck).
  2> {ok, Bin} = file:read_file("/tmp/fun_in_file").
  3> F = binary_to_term(Bin).
  4> F().
  ** exception error: bad function #Fun<ck.0.47723623>

What happened? The fun I stored is a reference to a fun which no
longer exists. The fun no longer exists because I changed the
module. I demonstrated it using a file and restarting the emulator,
but the same applies to other means of storing (e.g. dets) or sending
funs, including sending funs around in distributed Erlang (e.g. mnesia).

In the above example, Erlang did the right thing, i.e. it detected
that the fun had been changed. Due to a long-standing flaw, it's also
possible to change a fun without Erlang realising:



More information about the erlang-questions mailing list