0
votes

Given the list as input (in the format mentioned below) , I need to get the output that is a simple list of lists, If the given input list is empty then the predicate should return an empty list,

Given the input

[[[a,b],[c]],[[d,e]],[[g,h],[j,k]],[[h,k,l,l]]]

I need to get the output

[[a,b],[c],[d,e],[g,h],[j,k],[h,k,l,l]]

I am having trouble performing recursion,

The code I tried is below,

function([],X):-append([],X,X).
function([Head|Tail],X):-
                first(Tail,A),
                append(Head,A,X),
                removehead(Tail,C),
                function(C,X).

where the predicates first returns first element of the list, removehead removes the first element of the list.

1
Given the list as input (in the format mentioned above) , I need to get the output that is a simple list of lists, If the given input list is empty then the predicate should return an empty list. - sand
Put this in the question! - user1812457

1 Answers

1
votes

You make a fair attempt in the code you have shared. Here are the things that you need to improve:

  1. The predicate name fucntion describes the fact that this predicate has one solution whenever the first argument is a list. This is typically done in the documentation, e.g. %! function(+Nested:list, -Denested:list) is det.
  2. append([], X, X) is true by definition if X is a list, so it is superfluous here.
  3. What are first/2, removehead/2? If you want to instantiate to the first element of a list, you can also write the clause head argument as [Head,A|C]. Then you also do not need to remove the head from Tail explicitly.

Once I make alterations based on the above I come up with the following code:

%! denest(+Nested:list, -Denested:list) is det.

denest([], []).
denest([H|T1], L):-
  denest(T1, T2),
  append(H, T2, L).

Example run:

?- denest([[[a,b],[c]],[[d,e]],[[g,h],[j,k]],[[h,k,l,l]]], L).
   L = [[a, b], [c], [d, e], [g, h], [j, k], [h, k, l|...]].

Hope this helps!