简体   繁体   English

在Prolog中创建给定列表的平方根表

[英]Creating a table of square roots of a given list in Prolog

I am a newbie to Prolog and trying to develop a simple code to get the following output. 我是Prolog的新手,并尝试开发一个简单的代码来获取以下输出。

?-sqrt_table(7, 4, Result).
Result = [[4, 2.0],[7, 2.64575],[6, 2.44949],[5, 2.23607]] ;
false.

However the output I'm getting is, 但是我得到的输出是

?- sqrt_table(4,7,X).
X = [[5, 2.23606797749979], [[6, 2.449489742783178], [[7, 2.6457513110645907], []]]].

I think the issue is in the nested list created by get_sqrt/2. 我认为问题出在get_sqrt / 2创建的嵌套列表中。 If I can get it flattened down to tuples I think it might work. 如果我可以将其展平为元组,我认为它可能会起作用。 Your ideas and help are much appreciated. 非常感谢您的想法和帮助。

%main predicate
sqrt_table(N,M,Result):-
        full_list(N,M,Out),
        get_sqrt(Out,[Rest,Result]).

%Creates a range of outputs  within the given upper and lower limits
range(Low,Low,High).
range(Out,Low,High):-
        NewLow is Low+1,NewLow=<High,
        range(Out,NewLow,High).

%Creates a list of the outputs created by range/3
full_list(Low,High,Out):-
        findall(X,range(X,Low,High),Out).


%Calculates the square root of each item in the list and gives a list consisted
%of sublists such that [Input,Squareroot of the input]
get_sqrt([],[]).
get_sqrt([H|T],[[H,Sqrt],SqrtRest]):-
        SqrtOf_H is sqrt(H),
        get_sqrt(T,SqrtRest),
        Sqrt = SqrtOf_H.

Thanks in advance. 提前致谢。

In the head of the second clause of get_sqrt/2 , simply write [[H,Sqrt]|SqrtRest] , ie, use (|)/2 instead of (,)/2 . get_sqrt/2的第二个子句的get_sqrt/2 ,只需编写[[H,Sqrt]|SqrtRest] ,即使用(|)/2代替(,)/2

In fact, it would be even better to use the more readable and more idiomatic [H-Sqrt|HSqrts] , ie, use (-)/2 do denote pairs . 实际上,最好使用更具可读性和惯用性的[H-Sqrt|HSqrts] ,即使用(-)/2来表示

And in second fact, a better way altogether is to simply state the relation for one element at a time , using for example: 在第二个事实中,更好的方法是一次简单地一次声明一个元素的关系,例如:

integer_isqrt(I, I-Sq) :- Sq is sqrt(I).

and then to use the maplist/3 to relate lists of such elements to one another: 然后使用 maplist/3将此类元素的列表相互关联:

?- maplist(integer_isqrt, [0,1,2,3,4], Ls).
Ls = [0-0.0, 1-1.0, 2-1.4142135623730951, 3-1.7320508075688772, 4-2.0].

PS: Using flatten/2 always indicates a problem with your data structures, you should avoid flatten/2 entirely. PS:使用flatten/2始终表示您的数据结构有问题,应完全避免使用 flatten/2 If you need to remove one level of nesting, use append/2 . 如果需要删除一层嵌套,请使用append/2 But in this case, neither is needed. 但是在这种情况下,两者都不需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM