简体   繁体   中英

Chaning list elements in to a string

Let's say I have string as

L = [1, 2, 3]

I want to convert this list in to this

L1 = [one, two, three]

How can I do it?.

Take your pick:

Plain 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).

Same recursive concept but using a list of pairs for the lookup:

ints_words([], []).
ints_words([I|Is], [W|Ws]) :-
    
    Lookup = [1-one, 2-two, 3-three],

    member(I-W, Lookup),
    int_words(Is, Ws).

Similar, but using maplist instead of recursion:

int_word(I, W) :-
    member(I-W, [1-one, 2-two, 3-three]).

ints_words(Ints, Words) :-
    maplist(int_word, Ints, Words).

Similar but using a lambda to swap the arguments to member/2 and get rid of the second predicate (does Prolog have APL's anywhere?):

ints_words(Is, Ws) :-

    Lookup = [1-one, 2-two, 3-three],

    pairs_keys_values(Pairs, Is, Ws),
    maplist({Lookup}/[P]>>member(P, Lookup), Pairs).

Using SWI Prolog dictionary for the lookup which could be faster than member/2 if the number of lookups was larger, but likely makes no difference in such a small case:

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).

Using a grammar rule, (assuming the digit_name/2 facts from the plain Prolog example):

:- 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM