Prolog - 计算数字的出现次数 [英] Prolog - count occurrence of number

查看:65
本文介绍了Prolog - 计算数字的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个可以计算所有遇到的数字的谓词:

I want to write predicate which can count all encountered number:

count(1, [1,0,0,1,0], X).
X = 2.

我试着这样写:

count(_, [], 0).
count(Num, [H|T], X) :- count(Num, T, X1), Num = H, X is X1 + 1.

为什么不起作用?

推荐答案

为什么不起作用?

Why doesn't work it?

Prolog 是一种编程语言,通常可以直接回答此类问题.看看我是如何从失败的查询开始尝试你的定义的:

Prolog is a programming language that often can answer such question directly. Look how I tried out your definition starting with your failing query:

?- count(1, [1,0,0,1,0], X).
false.

?- count(1, Xs, X).
Xs = [],
X = 0 ;
Xs = [1],
X = 1 ;
Xs = [1, 1],
X = 2 ;
Xs = [1, 1, 1],
X = 3 ...

?- Xs = [_,_,_], count(1, Xs, X).
Xs = [1, 1, 1],
X = 3 ;
false.

所以首先我意识到查询根本不起作用,然后我概括查询.我用变量 Xs 替换了大列表并说:Prolog,为我填空!Prolog 做到了这一点,并准确地向我们展示了它何时会成功.

So first I realized that the query does not work at all, then I generalized the query. I replaced the big list by a variable Xs and said: Prolog, fill in the blanks for me! And Prolog did this and reveals us precisely the cases when it will succeed.

事实上,它只在 1 的列表中成功.这很奇怪.您的定义太受限制了 - 它正确地计算了只有 1 的列表中的 1,但所有其他列表都被拒绝.@coder 向您展示了如何扩展您的定义.

In fact, it only succeeds with lists of 1s only. That is odd. Your definition is too restricted - it correctly counts the 1s in lists where there are only ones, but all other lists are rejected. @coder showed you how to extend your definition.

这是另一个使用 library(reif)SICStus|SWI.或者,请参阅 tfilter/3.

Here is another one using library(reif) for SICStus|SWI. Alternatively, see tfilter/3.

count(X, Xs, N) :-
   tfilter(=(X), Xs, Ys),
   length(Ys, N).

一个定义更像其他定义:

A definition more in the style of the other definitions:

count(_, [], 0).
count(E, [X|Xs], N0) :-
   if_(E = X, C = 1, C = 0),
   count(E, Xs, N1),
   N0 is N1+C.

现在用于一些更一般的用途:

And now for some more general uses:

一个包含 3 个 1 的四元素列表是怎样的?

How does a four element list look like that has 3 times a 1 in it?

| ?- length(L, 4), count(1, L, 3).
     L = [1,1,1,_A],
     dif(1,_A)
  ;  L = [1,1,_A,1],
     dif(1,_A)
  ;  L = [1,_A,1,1],
     dif(1,_A)
  ;  L = [_A,1,1,1],
     dif(1,_A)
  ;  false.

所以剩下的元素必须与1不同.

So the remaining element must be something different from 1.

这就是 Prolog 为我们提供的一般性.

That's the fine generality Prolog offers us.

这篇关于Prolog - 计算数字的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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