gpt4 book ai didi

prolog - 如何计算一个字符在 Prolog 中的字符串列表中出现了多少次?

转载 作者:行者123 更新时间:2023-12-02 02:08:20 25 4
gpt4 key购买 nike

我想检查字符串中是否存在某个字符。所以 Atom 是字符串,Ch 是字符。 name 是一个谓词,它根据 ASCII 码转换数字列表中的字符串。

find_element 是一个谓词,只有当元素 X 是列表的一部分时才应为真。 C 是一个计数器,它告诉我们元素 X 的确切位置。

这是我得到的结果:

?- exists(prolog,g). [103][112,114,111,108,111,103] false.

------> 103 是字母“g”的 ASCII 码,列表 [112,114,111,108,111,103] 是表示字符串“prolog”的列表。问题 exists(prolog,g) 应该提供真实的响应。

但是 find_element 谓词工作正常。我不明白为什么会这样,因为当我输入例如

?- find_element(5,[3,4,5,6,5,2],X).

我得到 X= 3 ; X = 5 ;错误。 ---->

这绝对没问题,因为它告诉我 5 是列表的第 3 个和第 5 个元素。

所以问题是,当我输入类似 ?- find_element(5,[3,4,5,6,5,2],X) 的内容时,find_element 正在工作 但它不是当我尝试调用谓词存在时(它调用 find_element)。

这是代码:

find_element(X,[X|T],1).

find_element(X,[H|T],C):- find_element(X,T,TEMPC), C is TEMPC +1.

exists(Atom,Ch):- name(Atom,[X|T]), name(Ch,Z), write(Z), write([X|T]), find_element(Z,[X|T],Count).

提前致谢

最佳答案

我已经清理了一些你的代码,并修复了一个错误:

find_element(X,[X|_], 1).
find_element(X,[_|T], C) :-
find_element(X,T,TEMPC),
C is TEMPC +1.

exists(Atom, Ch):-
name(Atom, L),
name(Ch, [Z]),
find_element(Z, L, _Count).

注意 name(Ch, [Z]) 来提取单个字符。现在

?- exists(pippo,o).
true

值得注意的是

?- find_element(3, [1,2,3,4,1,2,3,4],P).
P = 3 ;
P = 7 ;
false.

?- nth1(P, [1,2,3,4,1,2,3,4], 3).
P = 3 ;
P = 7 ;
false.

您的 find_element/3 的行为与 nth1/3 相同,但交换了参数 1 和 3。

当然有更简单和更通用的方法来执行这样的测试。使用 ISO 内置函数喜欢sub_atom/5(一个非常强大的原子检查原语)

?- sub_atom(pippo, _,_,_, o).
true ;

或 memberchk/2,在转换为您已知的字符列表后(但使用 ISO 内置 atom_codes/2)

exists(Atom, Ch):-
atom_codes(Atom, L),
atom_codes(Ch, [Z]),
memberchk(Z, L).

要计算 sub_atom 的出现次数,可以使用 library(aggregate)

occurences(Atom, Ch, N) :-
aggregate_all(count, sub_atom(Atom, _,_,_, Ch), N).

?- occurences(pippo, p, X).
X = 3.

关于prolog - 如何计算一个字符在 Prolog 中的字符串列表中出现了多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13917513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com