0
votes

I'm studying prolog language and i have an issue regarding this problem.

I've already created a program that, given a number N, returns a list with elements between 0 and N:

list2val(N,L):- list2val(0,N,L).

list2val(N,N,[N]).
list2val(C,N,[C|T]):- 
    C<N,
    N1 is C+1,
    list2val(N1,N,T).

?- list2val(5,X).
X = [0,1,2,3,4,5]

Now i'm trying to give an extension that, given a list, returns a list of lists in which every list is list2val only if the next number is greater than current number. In this case:

?- newFuction([1,5,2,3,9],L). 
L = [[0,1],[0,1,2,],[0,1,2,3]]

My code is this, but somethings is wrong:

array(X):- array(X,_L).
array([],_L).

array([H|[T|Ts]],L1):- 
    H<T, 
    list2val(H,L2),
    array([T|Ts],[L1|[L2]]).
array([T|Ts],L1).

Maybe could be too much difficult to understand but using a list L = [1,5,2,3,9] i do those steps:

  • check 1<5 so i create a 1 list2val until 1..in this case [0,1]
  • check 5<2 i dont create nothing.
  • check 2<3 i create list2val of 2 ...[0,1,2]
  • and so on...

I don't want use a standard predicates, by implement with standard terms.

1
So you want to find a list (List) consisting of all numbers X between 0 and N? findall(X, between(0, N, X), List).firefrorefiddle
Nope.I want you to give a list, I find all the sublists (which are made up of numbers from 0 to N according to the function I have already done), and these lists are formed only if the current number is smaller than the next. @firefrorefiddle .. By the way i edit the question with another exampletheantomc
What happens when you call array([9], X)?Daniel Lyons

1 Answers

1
votes

A solution for your problem could be:

list2val(N,L):- list2val(0,N,L).

list2val(N,N,[N]):- !.
list2val(C,N,[C|T]):- 
    C<N,
    N1 is C+1,
list2val(N1,N,T).

simulate([_],[]).
simulate([A,B|T],[H|T1]):-
    ( A < B ->
        list2val(A,H),
        simulate([B|T],T1);
        simulate([B|T],[H|T1])
    ).

Using a predicate like simulate/2, you can solve your problem: it compares two numbers of the list and then create a new list in case the condition is satisfied.

?- simulate([1,5,2,3,9],LO).
LO = [[0, 1], [0, 1, 2], [0, 1, 2, 3]]
false