0

I am trying to write a program which make the following:

?- g([2,3, [22,[3],9] ,4,[5],99],X).

X= [2,3,22,[3],9 ,4,5,99]

so it searches for lists in the given list and replace it by their elements without brackets [].

so I wrote this program:

The first block just searches for the first element in the list which is list
If there is no such element it returns [there_is_no_list].

first_list_in_the_list([],[there_is_no_list]):-!.  
first_list_in_the_list([H|_],X):-is_list(H),X=H,!.  
first_list_in_the_list([_|T],X):-first_list_in_the_list(T,X).

The first block works in prolog perfectly.

The second block just search in the list for an element X and then split the list into a two lists one is the list of all elements before X and the second is the elements after X.

splite_when_find_element([H|T],H,[],T):-!.  
splite_when_find_element([H|T],X,F,G):-
    splite_when_find_element(T,X,F1,G),append([H],F1,F).

it also works fine in Prolog.

and the third block is append, and it joins two list together in a new list.

append([],L,L).  
append([H|T],L,[H|U1]):- append(T,L,U1).

and the last part is:

gg(L,L):-first_list_in_the_list(L,[there_is_no_list]),!.    
gg(L,U):-first_list_in_the_list(L,X),
         splite_when_find_element(L,X,F,G),gg(G,R),append(F,X,E),
         append(E,R,U).

when I give a query [2,[3],5] I get also [2,[3],5] and I really don't understand why it does this.

  • why didn't you ask at Stack Overflow? – gnat Aug 8 '13 at 14:19
-1

Your logic is flawed. Your first_list_in_the_list function looks for an empty list or a list with more than one element. The one element list gets ignored.

| improve this answer | |
  • i didn't get what your idea is, when i apply the code first_list_in_the_list([1],X), i get the crrect answer which is X=[the_is_no_list], and if I apply first_list_in_the_list([[1]],X), i get X=[1], i don't think the fault is in first_list_in_the_list . – Kemo Aug 8 '13 at 16:20
  • There is a list [3] is a list with one element. – Michael Brown Aug 8 '13 at 17:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.