iDev
iDev

Reputation: 2433

Shallow predicate to square each number in the list

I am trying to want to create a shallow predicate called say square to square each number in the list example :

e.g. ?-square([a,[[3]],b,4,c(5),8],X).
       X=[a,[[3]],b,16,c(5),64]

Upvotes: 1

Views: 1145

Answers (1)

Fred Foo
Fred Foo

Reputation: 363807

Trivial.

sq(X) :-
    number(X) -> X2 is X*X ; X2 = X.

square(List, Squared) :-
    maplist(sq, List, Squared).

But note that square([X], X2), X=2 will not have the desired effect.

Upvotes: 2

Related Questions