Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 如何在列表序言中获得一半的元素数_List_Prolog - Fatal编程技术网

List 如何在列表序言中获得一半的元素数

List 如何在列表序言中获得一半的元素数,list,prolog,List,Prolog,我有一个谓词,它给出列表中元素的数量 get_elements([],0). get_elements([_|Tail], N) :- get_elements(Tail, N1), N is N1 + 1. ?- get_elements([1,1,1,1,1,1],N). N = 6. 但是我想要6个,而不是3个。我怎样才能更改谓词来实现这一点 谢谢 如果列表中有奇数个元素,您还没有说明希望发生什么。但我假设你想得到那样的结果 一种强力但简单的方法是使用length/2: count_

我有一个谓词,它给出列表中元素的数量

get_elements([],0).
get_elements([_|Tail], N) :- get_elements(Tail, N1), N is N1 + 1.


?- get_elements([1,1,1,1,1,1],N).
N = 6.
但是我想要6个,而不是3个。我怎样才能更改谓词来实现这一点


谢谢

如果列表中有奇数个元素,您还没有说明希望发生什么。但我假设你想得到那样的结果

一种强力但简单的方法是使用
length/2

count_half(List, HalfCount) :- length(List, N), HalfCount is N div 2.
对于元素数为奇数的列表,它将给出元素数减去1的一半(例如,7个元素将产生3的结果)

一种简单的递归方法(对于列表处理更具指导意义)是稍微更改您的实现:

count_half([], 0).
count_half([_,_|Tail], N) :-
    count_half(Tail, N1),
    N is N1 + 1.
这将对每对元素进行计数。唯一的缺点是,如果元件数量为奇数,则会导致故障。可通过一个额外的基本情况进行补救:

count_half([], 0).
count_half([_], 0).
count_half([_,_|Tail], N) :-
    count_half(Tail, N1),
    N is N1 + 1.

提示:使用兔子和乌龟的方法。将
+1
更改为
+0.5