将列表分成两半 [英] Split a list in half

查看:76
本文介绍了将列表分成两半的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义划分,以便列表[1,2,3,4,5]划分为:

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

a = [1,2,3}

b = [4,5]

我遇到一个错误,提示"Arguments are not sufficiently instantiated",并且我对该语言的了解还不足以找出问题所在,或者我的设计是否正确.任何指导将不胜感激.

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_half_half/3

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/2append/3在几乎所有最近的Prolog中都是预定义的.

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

这是GNU Prolog:

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]

这篇关于将列表分成两半的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆