Google Groups

Re: Passing a fun that executes in repl to another function fails?


Garrett Smith Feb 27, 2011 10:58 PM
Posted in group: erlangcamp
Does this fail each and every time you run it? You have a "random"
element in your example -- could that be throwing off an occasional
bad value?

I'd want to know what values were going into gaeqn:compute/2 that were
causing the error before thinking too hard about it. Can you throw in
an io:format/2 call somewhere to print your inputs?

On Sun, Feb 27, 2011 at 8:36 PM, Bill Robertson
<billrob...@gmail.com> wrote:
> I wrote a timer function which, takes a number of iterations and a
> fun, after executing N times, it returns the number of microseconds.
> It was doing fine until I gave it the following fun.
>
> 168> F = fun() -> gaeqn:evaluate(42,
> gaeqn:tokenize(gaeqn:random_chromosome(20))) end.
> #Fun<erl_eval.20.67289768>
> 169> F().
> {1.609082951444313e-6,
>  [7,"+",6,"*",217909,"-",7,"+",2760820,"/",9],
>  621514}
>
> You can see that the fun executes w/o error, but when passing it to
> the timer, something bombs.
>
> 170> gaeqn:timer(200, F).
> ** exception error: bad argument in an arithmetic expression
>     in function  gaeqn:compute/2
>     in call from gaeqn:evaluate/2
>     in call from gaeqn:timer/3
>
> The timer code appears to work.  Please see the code snippet below.
>
> 172> gaeqn:timer(200, fun() -> now() end).
> 307
> 173> N = fun() -> now() end.
> #Fun<erl_eval.20.67289768>
> 174> gaeqn:timer(200, N).
> 224
>
> Here is the timer code.
>
> timer(N, Fun) when N > 0 ->
>    timer(now(), N, Fun).
>
> timer(Start, 0, Fun) ->
>    Fun(),
>    timer:now_diff(now(), Start);
> timer(Start, N, Fun) ->
>    Fun(),
>    timer(Start, N-1, Fun).
>
> Any ideas why the two wouldn't work together?
>