[英]Chaning list elements in to a string
假设我有字符串
L = [1, 2, 3]
我想将此列表转换为
L1 = [one, two, three]
我该怎么做?。
随你选:
普通 Prolog:
digit_name(0, zero).
digit_name(1, one).
digit_name(2, two).
digit_name(3, three).
digit_name(4, four).
digit_name(5, five).
digit_name(6, six).
digit_name(7, seven).
digit_name(8, eight).
digit_name(9, nine).
digits_names([], []).
digits_names([D|Ds], [N|Ns]) :-
digit_name(D, N),
digits_names(Ds, Ns).
相同的递归概念,但使用成对列表进行查找:
ints_words([], []).
ints_words([I|Is], [W|Ws]) :-
Lookup = [1-one, 2-two, 3-three],
member(I-W, Lookup),
int_words(Is, Ws).
类似,但使用 maplist 而不是递归:
int_word(I, W) :-
member(I-W, [1-one, 2-two, 3-three]).
ints_words(Ints, Words) :-
maplist(int_word, Ints, Words).
类似但使用 lambda 将 arguments 交换为member/2
并摆脱第二个谓词(Prolog 是否有 APL 的⍨
任何地方?):
ints_words(Is, Ws) :-
Lookup = [1-one, 2-two, 3-three],
pairs_keys_values(Pairs, Is, Ws),
maplist({Lookup}/[P]>>member(P, Lookup), Pairs).
使用 SWI Prolog 字典进行查找,如果查找的数量更大,这可能比member/2
更快,但在这么小的情况下可能没有区别:
int_word(Dict, Int, Word) :-
get_dict(Int, Dict, Word).
ints_words(Ints, Words) :-
Lookup = names{1:one, 2:two, 3:three},
maplist(int_word(Lookup), Ints, Words).
使用语法规则,(假设来自普通 Prolog 示例的 digit_name/2 事实):
:- use_module(library(dcg/basics)).
ds_ns([N|Ns]) --> [D], {digit_name(D, N)}, ds_ns(Ns).
ds_ns([]) --> eos.
-- e.g.
?- phrase(ds_ns(Names), [3,2,2,1]).
Names = [three, two, two, one]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.