开发者

Is there a way to use local function in guard

开发者 https://www.devze.com 2023-03-16 08:06 出处:网络
Here is my code: is_prime(Num)-> length(list_of_dividers(Num)) == 0. problem_7(Current, Primes, Counter) when Primes >= 10001->

Here is my code:

is_prime(Num)->
    length(list_of_dividers(Num)) == 0.

problem_7(Current, Primes, Counter) when Primes >= 10001->
    Current;
problem_7(Current, Primes, Counter) when is_prime(Counter) ->
    problem_7(Counter, Primes + 1, Counter + 1);
problem_7(Current, Primes, Counter) ->
    problem_7(Current, Primes, Counter).

I get error:

32> c(problem_7).
./problem_7.erl:30: call to local/imported function is_prime/1 is illegal in guard

An开发者_运维百科d i can not use local function in the 'if'-expression:

if is_prime(Counter)->
    problem_7(Counter, Primes + 1, Counter + 1);
   true ->
    problem_7(Current, Primes, Counter + 1)
end.

I am just wondering if there is any way to use local function in guard and how can I write condition with local function?


The reason for restricting the set of valid expressions is that evaluation of a guard expression must be guaranteed to be free of side effects. http://www.erlang.org/doc/reference_manual/expressions.html (section 7.24)

Use case statement inside your function. You should be able to use local function in if and case.

Edited: Agree with @cthulahoops, I was wrong about if http://www.erlang.org/doc/reference_manual/expressions.html#id75927

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号