[erlang-questions] DRY principle and the syntax inconsistency in fun vs. vanilla functions

Frédéric Trottier-Hébert fred.hebert@REDACTED
Wed May 18 23:50:29 CEST 2011


On 2011-05-18, at 17:40 PM, Joe Armstrong wrote:

> 
> 
> 
> Me, I'd like to say
> 
>    L = [{foo, fun(X,Y) -> ... end}, {bar, fun(X) -> ... end}]
> 
>    then have couple of new bifs Mod = list_to_mod(L) to compose
> a module from a load of funs and mod_to_list to do the inverse.
> 
>   
> 
> /Joe
> 
>  
I think you would enjoy meck then (https://github.com/eproxus/meck):


Eshell V5.7.5  (abort with ^G)
1> meck:new(dog).
ok
2> meck:expect(dog, bark, fun() -> "Woof!" end).
ok
3> dog:bark().
"Woof!"

It lets you do that, and it includes more testing facilities (expectations, exceptions, history of calls, etc.), but it has some core features that do what you want. One issue of doing things that way is that it's impossible to do recursion without cheating and basically embedding a y-combinator in your code*

*:
4> meck:expect(dog, rec, fun(X) -> 
4>    F = fun(F,0) -> io:format("~p~n",[0]);
4>                (F,Y) -> io:format("~p~n",[Y]),
4>                               F(F,Y-1) 
4>          end,
4>    F(F,X)
4> end).
ok
5> dog:rec(3).                                                                                                                       
3
2
1
0
ok


--
Fred Hébert
http://www.erlang-solutions.com





More information about the erlang-questions mailing list