Split a list in half

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

    Let's give the predicate a more relational name: list_half_half/3

    list_half_half(Xs, Ys, Zs) :-
       length(Xs, N),
       H is N - N // 2,
       length(Ys, H),
       append(Ys, Zs, Xs).
    

    length/2 and append/3 are predefined in practically all recent Prologs.

    This is GNU Prolog:

    | ?- append(L,_,[a,b,c,d]), list_half_half(L,H1,H2).
    
    H1 = []
    H2 = []
    L = [] ? ;
    
    H1 = [a]
    H2 = []
    L = [a] ? ;
    
    H1 = [a]
    H2 = [b]
    L = [a,b] ? ;
    
    H1 = [a,b]
    H2 = [c]
    L = [a,b,c] ? ;
    
    H1 = [a,b]
    H2 = [c,d]
    L = [a,b,c,d]
    

提交回复
热议问题