The inverse of a function...

Erik Stenman Erik.Stenman@REDACTED
Wed Mar 10 11:09:28 CET 2004


Corrado Santoro wrote:
> Hi Erlang gurus,
> I have a function like this:
> 
> f(caesar) -> ...;
> f(caius) -> ....;
> f(giulius) -> ....
>
> I would like to have a function that, given the name 'f', returns the 
> list [caesar, caius, giulius] (or similar).
> Is it possibile to do this (obviously without re-interpreting the 
> source file)?

Actually, contrary to what has been said before on this list 
by very knowledgeable persons, it is possible, at least as long 
as the function f has no side effects, and the arguments are only
atoms.

 -module(hack).
 -export([find_keys/2,f/1]).

 find_keys(Module,FunctionName) ->
 
{value,{atoms,As}}=lists:keysearch(atoms,1,element(2,beam_disasm:file(Module
))),
    Atoms = [A || {_,A} <- As],
    [A || A <- Atoms, 
          case catch apply(Module,FunctionName,[A]) of 
          {'EXIT',_} -> false; 
          _ -> true 
    end].

 f(caesar) -> 1;
 f(caius) -> 2;
 f(giulius) -> 3.


---
19> c(hack).               
{ok,hack}
20> hack:find_keys(hack,f).
[giulius,caius,caesar]
21> 


OK, I know it is a hack, but what the heck, I could not resist.

Erik




More information about the erlang-questions mailing list