Split a list in half

后端 未结 7 1394
滥情空心
滥情空心 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:05

    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.

提交回复
热议问题