Search code examples
prolog

prolog generate list of numbers from a list[x,y]


Hello I want to generate a list as following. Given a list like [x,y] I want to generate a list that is x,x,...,x : y times eg [2,3]=[2,2,2] but I cannot figure out how.

This is my implementation so far:

generate([T,1],[T]).
generate([X,S],[X|T]):-S1 is S-1,generate([X,S1],[T]).

but for some reason it fails. Can you help me?


Solution

  • The problem is in your second clause. When you have [X|T], it means that T is a list. In the body you write generate([X,S1],[T]): by writing [T] you're now saying the second argument to generate is a list of which the only element is this list T. What you want to say is that it is simply this list T:

    generate([T,1], [T]).
    generate([X,S], [X|T]) :- S1 is S-1, generate([X,S1], T).