将字符串转换为序言中的列表 [英] convert string to list in prolog
问题描述
我是 Prolog 新手,我一直在将字符串解析为列表.我有一个
I am a Prolog newbie and am stuck at parsing a string to a list. I have a string of the form
1..2...3..4
我想把它转换成一个看起来像的列表
I wish to convert it into a list which looks like
[1, _, _, 2, _, _, _, 3, _, _, 4]
我怎样才能实现这个功能?
How can I achieve this functionality?
推荐答案
另一种解决方案是使用 DCG.代码很简单:
Another solution is to use DCG's. The code is straightforward:
digit(N) -->
[ D ], { member(D, "0123456789"), number_codes(N, [D]) }.
dot(_) --> ".".
token(T) --> digit(T).
token(T) --> dot(T).
tokens([T|Ts]) --> token(T), tokens(Ts).
tokens([]) --> "".
parse_codes(In, Out):-
phrase(tokens(Out), In, "").
parse_atom(In, Out):-
atom_codes(In, Codes),
parse_codes(Codes, Out).
使用字符串"(实际上只是代码列表)在 SWI-Prolog 上进行测试:
Testing on SWI-Prolog with "string" (which is actually just a list of codes):
?- parse_codes("1..24.4", Out).
Out = [1, _G992, _G995, 2, 4, _G1070, 4] .
还有一个原子(在使用相同谓词之前只是转换为代码):
And with an atom (which is just converted to codes before using the same predicate):
?- parse_atom('1..22.4', Out).
Out = [1, _G971, _G974, 2, 2, _G1049, 4] .
SWI-Prolog 以更高级的符号打印匿名变量 (_),否则它应该与您需要的结果相同.
SWI-Prolog prints anonymous variables (_) in a bit fancier notation but otherwise it should be the same result you need.
这篇关于将字符串转换为序言中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!