rnso
rnso

Reputation: 24623

Simple square program in Prolog

Why is following simple program not working?

main :-
    squares([1,2,3,4,5], L),
    writeln(L).

squares([H|T], Outl) :-
    Sq is H*H,
    squares(T, [Sq|Outl]).
squares([], []).

The output is:

?- main.
false.

Replacing Outl with [Outl] ( in squares([H|T], Outl) ) does not help.

Using = and #= instead or is also did not help.

Nor did squares([], P) instead of squares([], []).

Upvotes: 2

Views: 1513

Answers (2)

lurker
lurker

Reputation: 58324

This is a great candidate for maplist.

Define squaring of one element:

squared(X, XX) :- XX #= X * X.

Then apply maplist:

squared_list(L, LL) :- maplist(squared, L, LL).

By using #= here instead of is/2, it's behavior is more relational:

| ?- squared_list([1,2,3], L).

L = [1,4,9]

yes
| ?- squared_list(L, [1,4,9]).

L = [1,2,3] ? ;

(1 ms) no
| ?-

Upvotes: 4

joel76
joel76

Reputation: 5645

Look at what you have written

squares([H|T],Outl):-
    Sq is H*H,
    squares(T,[Sq|Outl]).

Sq is misplaced, you should write

squares([H|T],[Sq|Outl]):-
    Sq is H*H,
    squares(T,Outl).

You add Sq at the result of the computation of the rest of the list T.

Upvotes: 1

Related Questions