开发者

Prolog flatten list

flatten([A|B],R):- (islist(A)->(flatten(A,R1),R=R1);(write(A),append([A],R1,R))), flatten(B开发者_JAVA百科,R1).
    flatten(X,X).
    islist([_|_]).

This is the code i written but i have strange problem..

I get

257 ?- flatten([1,[],2,[3],[3,[3,5]]],R).
1[]23335335
R = [1, [], 2, [3], [3, [3, 5]]] .

Although the numbers from write are not list they are appended as list:S...


There are some errors in your definition of flatten/2:

Your first clause will fail because if A is a list it will first instantiate R1 with R and then you try to unify it again with flatten(B, R1).

flatten(X,X). -> This clause leaves the list 'as is' without any flattening.

Check this other implementation:

flatten(List, Flattened):-
  flatten(List, [], Flattened).

flatten([], Flattened, Flattened).
flatten([Item|Tail], L, Flattened):-
  flatten(Item, L1, Flattened),
  flatten(Tail, L, L1).
flatten(Item, Flattened, [Item|Flattened]):-
  \+ is_list(Item).

Here we use two predicates: flatten/2 and flatten/3. The 'work' will be done in flatten/3 where the second argument will hold the intermediate flattened list.

The first clause is the base case: when we reach the empty list we are done so we instantiate the third argument with the intermediate flattened list.

The second clause deals with recursion. It flattens the first item in the list (whether it is an item or a sublist), and proceeds with the rest of the input list.

The last clause is the 'base case' for the non-lists items. It prepends the item at the beginning of the intermediate flattened list, but it only does this for items which are not lists as that case was taken care in the second clause.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜