Split a list in half

后端 未结 7 1414
滥情空心
滥情空心 2020-12-19 03:25

I need to define divide so that List [1,2,3,4,5] divides into:

a = [1,2,3}

b = [4,5]

I\'m getting an error that says \"

7条回答
  •  鱼传尺愫
    2020-12-19 04:17

    This is the most efficient solution conforming to your specification for most Prolog implementations:

    divide(L, A, B) :-
        divide1(L, L, A, B).
    
    divide1([], L, [], L).
    divide1([_|T], [H|L], [H|A], B) :-
        divide2(T, L, A, B).
    
    divide2([], L, [], L).
    divide2([_|T], L, A, B) :-
        divide1(T, L, A, B).
    

    If you don't mind which elements go into the sublists as far as they are of similar length (as in the solution from Konstantin Weitz post), then you can use :

    divide([], [], []).
    divide([H|T], [H|A], B) :- divide(T, B, A).
    

提交回复
热议问题