Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

erlang - Use of function in Guard not allowed. Suggestions for alternate implementation wanted

I am attempting to create a prime number factorizer, using fermats method.

This line generates an error

find_factors(A, B, FactorThis) when is_a_square(B) == true ->

call to local/imported function is_a_square/1 is illegal in guard

The only possible alternative I see to this implementation is to use some sort of case statement within the function. I was avoiding that, as it might screw up the tail recursion. I am a Erlang noob. What other ways are there to implement this functionality?

get_int_part_of_sqrt(N) ->
    trunc(math:sqrt(N)).

is_a_square(N) ->
    get_int_part_of_sqrt(N) * get_int_part_of_sqrt(N) == N.

calculate_new_b(A, FactorThis) ->
    NewB = trunc(abs((A * A) - FactorThis)),
    io:format("Calculate_new_b A^2 ~w- FT ~w= NB ~w ~n",[A*A,FactorThis,NewB]),

find_factors(A, B, FactorThis) when is_a_square(B) == true ->
    io:format("find_factors true ~w ~w~n", [A, B]),
    {ok, A + get_int_part_of_sqrt(B), A - get_int_part_of_sqrt(B)};

find_factors(A, B, FactorThis) ->
    io:format("find_factors false ~w ~w~n", [A, B]),
    NewA = A + 1,
    NewB = calculate_new_b(NewA, FactorThis),
    find_factors(NewA, NewB, FactorThis).

Research1

Research2

Edited. fixed argument in call to calculate_new_b

added missing get_int_part_of_sqrts.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Erlang deliberately restricts which functions you're allowed to call in guards. Here's a fairly recent discussion of the justification for this, its merits and drawbacks.

The only way around it is to use case. You can pretty easily rewrite this code to use case:

find_factors(A, B, FactorThis) ->
    case is_a_square(B) of
        true -> io:format("      find_factors true ~w ~w~n", [A, B]),
                {ok, A + B, A - B};

        false-> io:format("      find_factors false ~w ~w~n", [A, B]),
                NewA = A + 1,
                NewB = calculate_new_b(NewA, FactorThis),
                find_factors(NewA, NewB, FactorThis).

Note that the above code is still properly tail-recursive.

(I modified your code a little to take out the parts that I'm guessing you meant not to have there)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...