[英]Converting a string list to integer in swi prolog as shown
How to convert a string list to integers? 如何将字符串列表转换为整数? Eg: if the list is ['i','am','fine'], the result should be [9,14,34] (i=9,am=1+13=14,fine=6+9+14+5=34) 例如:如果列表为['i','am','fine'],则结果应为[9,14,34](i = 9,am = 1 + 13 = 14,fine = 6 + 9 + 14 + 5 = 34)
How do I do this in SWI Prolog? 如何在SWI Prolog中做到这一点?
If you have module lambda ( http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl ) you can write 如果您有模块lambda( http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl ),则可以编写
:- use_module(library(lambda)).
convert(Lst, Val) :-
maplist(\X^Y^(atom_codes(X, Ch),
foldl(\Z^T^U^(U is T + Z-96),Ch, 0, Y)), Lst, Val).
convert(Atoms, Values) :-
maplist(a2n, Atoms, Values).
a2n(Atom, Num) :-
atom_codes(Atom, Cs),
[A] = "a",
maplist(sub(A), Cs, L),
sumlist(L, Num).
sub(A, C, N) :- N is C - A + 1.
The program can be built with a single built-in predicate, atom_codes
and the standard recursion facilities of the language. 可以使用单个内置谓词, atom_codes
和该语言的标准递归工具构建该程序。
You need two rules - one to transform a list item-by-item to another list, and another one to total up the codes from which an atom is composed. 您需要两个规则-一个规则将一个项目逐个列表转换为另一个列表,另一个规则以汇总组成原子的代码。
Each rule would have two parts - one to process the base case (ie an empty list), and one to reduce the incoming list by one item. 每条规则将包含两个部分-一个部分处理基本情况(即空列表),另一个部分将传入列表减少一项。
Here is a sample implementation with a demo on ideone : 这是带有ideone演示的示例实现:
sum_atoms([], []).
sum_atoms([H|T], [HeadSum|RT]) :-
atom_codes(H, Codes),
sum_letters(Codes, HeadSum),
sum_atoms(T, RT).
sum_letters([], 0).
sum_letters([H|T], Res) :-
sum_letters(T, TailSum),
Res is (H-96) + TailSum.
If you would like to use maplist/3
and sumlist/2
, built-in predicates for list processing, you can shorten your program like this: 如果您想使用sumlist/2
maplist/3
和sumlist/2
内置谓词进行列表处理,则可以这样缩短程序:
sum_atoms(In, Out) :-
maplist(sum_letters, In, Out).
sum_letters(Atom, Sum) :-
atom_codes(Atom, Codes),
maplist(plus(-96), Codes, LetterNumbers),
sumlist(LetterNumbers, Sum).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.