Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should i define something constantlike in Erlang

I have a module which does some non constrained minimization. I'd like to keep its' interface as simple as possible, so the best choice would be to reduce it to a single function something like: min_of( F ).

But as soon as it is brutal computation, i would have to deal with at least two constants: precision of minimization algorithm and maximum number of iterations, so it would not hang itself if target function doesn't have local minimum at all.

Anyways, the next best choice is: min_of( F, Iterations, Eps ). It's ok, but I don't like it. I would like to still have another min_of( F ) defined something like this:

min_of( F ) ->
    min_of( F, 10000, 0.0001).

But without magic numbers.

I'm new to Erlang, so I don't know how to deal with this properly. Should i define a macros, a variable or maybe a function returning a constant? Or even something else? I found Erlang quite expressive, so this question seems to be more of a good practice, than technical question.

like image 236
akalenuk Avatar asked Jun 02 '12 10:06

akalenuk


2 Answers

You can define macros like this

-define(ITERATIONS, 10000).
-define(EPS, 0.0001).

and then use them as

min_of(F, ?ITERATIONS, ?EPS).
like image 181
spicavigo Avatar answered Nov 02 '22 14:11

spicavigo


You can use macros but you can also use in-lined functions.

-compile({inline, [iterations/0, eps/0]}).

iterations() -> 10000.
eps() -> 0.0001.

and then use it in the way

min_of(F) ->
  min_of(F, iterations(), eps()).

The benefit is you can use all syntax tools without need of epp. In this case also calling of function is not performance critical so you can even go without inline directive.

like image 31
Hynek -Pichi- Vychodil Avatar answered Nov 02 '22 14:11

Hynek -Pichi- Vychodil