0
votes

Let's say I want to construct a list with 10 elements where each elements can be 0 or 1 or 2. What I have are two lists List1 and List2, they are the positions of those 1 and 2. So how can I construct the whole list using a function like this:

construct(List1,List2,L).

example:

Input:

construct([1,3,5],[8],L)

Output:

L = [1,0,1,0,1,0,0,2,0,0]
1
Actually I already implement a function replace(L,pos,num,Lnew) to replace the pos-th element in L by num and put the new list into Lnew, but I just don't know how to use this function to implement the construct function.Jasmine233
You really need to show in your question everything relevant that you have.user1812457

1 Answers

0
votes

What about

constructH(Top, Top, _, _, []).

constructH(Num, Top, L1, L2, [1 | Ho]) :-
  Num < Top,
  member(Num, L1),
  Np1 is Num+1,
  constructH(Np1, Top, L1, L2, Ho).

constructH(Num, Top, L1, L2, [2 | Ho]) :-
  Num < Top,
  member(Num, L2),
  Np1 is Num+1,
  constructH(Np1, Top, L1, L2, Ho).

constructH(Num, Top, L1, L2, [0 | Ho]) :-
  Num < Top,
  \+ member(Num, L1),
  \+ member(Num, L2),
  Np1 is Num+1,
  constructH(Np1, Top, L1, L2, Ho).


construct(List1, List2, Lout) :-
  constructH(1, 11, List1, List2, Lout).

?