Skip to content

Instantly share code, notes, and snippets.

@krestenkrab
Created April 12, 2011 09:52
Show Gist options
  • Save krestenkrab/915264 to your computer and use it in GitHub Desktop.
Save krestenkrab/915264 to your computer and use it in GitHub Desktop.
The programmatic counter-part for "fun Mod:Fun/Arity"
-module(funhack).
-export([mkfun/3]).
%% @doc
%% The programmatic counter-part for `fun Mod:Fun/Arity'.
%%
%% Erlang syntax does not allow usage of the `fun' syntax,
%% where Mod, Fun and Arity are variables; they need to be
%% atom, atom, integer. This little hack lets you avoid
%% writing `fun(A1,A2,A3...) -> Mod:Fun(A1,A2,A3,...) end'.
%% @end
mkfun(Mod,Fun,Arity) ->
ModBin = atom_to_binary(Mod, latin1),
FunBin = atom_to_binary(Fun, latin1),
Binary = <<131,113,
100,0,(byte_size(ModBin)),ModBin/binary,
100,0,(byte_size(FunBin)),FunBin/binary,
97,Arity>>,
binary_to_term(Binary).
@richcarl
Copy link

Oooh, Kresten, you so nasty! ;-)

@djui
Copy link

djui commented Apr 12, 2011

Nice hack. btw: what's wrong with using erlang:make_fun/3?

@krestenkrab
Copy link
Author

Darn, even Erjang implements it. Stupid me; but it is not documented!

@richcarl
Copy link

No, it's really meant as a compiler intrinsic function, and should not be used by mere mortals. It might be preferable to the binary_to_term-hack, though, if you really really need it. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment