Flatten a list in Prolog

后端 未结 7 731
执笔经年
执笔经年 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:29

    Here's an accumulator based version for completeness:

    % flatten/2
    flatten(List, Result) :- flatten(List, [], Result).
    
    % auxiliary predicate flatten/3
    flatten([], Result, Result).
    flatten([Head| Tail], Part, Result) :- 
        is_list(Head),
        !, 
        flatten(Head, HR),
        append(Part, HR, PR),
        flatten(Tail, PR, Result).
    flatten([Head| Tail], Part, Result) :- 
        append(Part, [Head], PR),
        flatten(Tail, PR, Result).
    flatten(X, Part, Result) :-
        fail.
    

提交回复
热议问题