简体   繁体   中英

Having a List as an element in the list Prolog

Given a list (List1), I am trying to square each number in the list and return the answers in a new list (List2), where each element in List2 is in the form (Xi, Ji).

?- square([1,2,3,], L).
L = [[1,1],[2,4],[3,9]].

This is my code:

square([], []).
square([N|Tail], [SqrdN|SqrdTail]) :-
    SqrdN is [N|N*N],
    square(Tail, SqrdTail).

This is giving me a type error: '[]' expected, found `[1|1*1]' (a compound) ("x" must hold one character).

How can I achieve this?

You are mixing your output representation (lists of [Item, SquaredItem] ) with the computation of the squares, and your output term is also not a proper list of two items.

Using library clpfd:

:- use_module(library(clpfd)).
square([], []).
square([N|Tail], [[N, SqrdN]|SqrdTail]) :-
    SqrdN #= N*N,
    square(Tail, SqrdTail).

or without clpfd:

square([], []).
square([N|Tail], [[N, SqrdN]|SqrdTail]) :-
    SqrdN is N*N,
    square(Tail, SqrdTail).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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