Xavier MA
Xavier MA

Reputation: 13

Write a predicate sqrt_list(NumberList, ResultList) to the list of pairs consisting of a number and its square root

Write a predicate sqrt_list(NumberList, ResultList) that binds ResultList to the list of pairs consisting of a number and its square root, for each number in NumberList.

For example:

?- sqrt_list([1,4,9], Result).
Result = [[1,1.0], [4,2.0], [9,3.0]].  % expected

Upvotes: 1

Views: 207

Answers (2)

Sanchita KR
Sanchita KR

Reputation: 1

keep dividing the original list into sublist, taking one number as head and rest as a tail. repeat the same and Note that the Prolog built-in function sqrt computes the square root and that it needs to be evaluated using is to actually do the computation: example:

?- X is sqrt(5).
X = 2.23606797749979.

then add each result to the resultList head with numberList. as,

 ResultHead=[Head|[SquareRoot]]

Upvotes: 0

repeat
repeat

Reputation: 18726

Using the meta-predicate maplist/3 in combination with library(lambda):

:- use_module(library(lambda)).

list_withsqrts(Es, Xss) :-
   maplist(\E^[E,S]^(S is sqrt(E)), Es, Xss).

Sample query:

?- list_withsqrts([1,4,9], Xss).
Xss = [[1,1.0], [4,2.0], [9,3.0]].

A few notes:

  1. Using fixed-length lists instead of compound terms of the same arity is generally regarded as bad coding style.

  2. Finding good relation names is an important Prolog programming skill. In above code I used list_withsqrts instead of sqrt_list. Not famous, but arguably somewhat better...

Upvotes: 2

Related Questions