Flatten a list in Prolog

后端 未结 7 683
执笔经年
执笔经年 2020-11-27 08:00

I\'ve only been working with Prolog for a couple days. I understand some things but this is really confusing me.

I\'m suppose to write a function that takes a list

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 08:27

    I didn't find a solution using findall, so I'll add it. (it will work if the list is ground)

    First, we define how to test for a list:

    list(X) :- var(X), !, fail.
    list([]).
    list([_|_]).
    

    and the transitive closure of member, we call it member*:

    'member*'(X, Y) :- member(X, Y).
    'member*'(X, Y) :- member(Z, Y), 'member*'(X, Z).
    

    The flattened list is all the solution of member* which are not lists:

    flatten(X, Y) :- findall(Z, ('member*'(Z, X), \+ list(Z)), Y).
    

    Example:

    ?- flatten([[4],[[5,6],[7,[8],[9,[10,11]]]]],Y).
    Y = [4, 5, 6, 7, 8, 9, 10, 11].
    

提交回复
热议问题