Split a list in half

2020-02-12 04:42发布

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 "Arguments are not sufficiently instantiated", and I don't know enough about the language to figure out what my problem is, or if my design is even right. Any guidance would be appreciated.

So here's what I have so far:

append([],L2,L2).
append([H|T],L2,[H|L3]) :- append(T,L2,L3).

lengthIs([],N).
lengthIs([H|T],N) :- lengthIs(T,M), N is M+1.

divide([],[],[]).
divide([H|T],L2,L3) :-
   (  lengthIs(L2, M) < lengthIs(L1,N)/2
   -> divide(T, append(L2, H, X), L3)
   ;  divide(T, L2, append(L3,H,Y))
   ).

标签: list prolog
7条回答
戒情不戒烟
2楼-- · 2020-02-12 05:13

Another answer, uses Backtracking a lot, isn't very performant, though. append and length are assumed to be predefined:

divide(A,B,C):-
    append(B,C,A),
    length(B,B_Length),
    length(C,C_Length),
    (B_Length = C_Length;
        B_Length =:= C_Length +1).

Oh, sorry, just have seen that this is sort of a rephrasing of the answer from Philip Whitehouse.

查看更多
登录 后发表回答