Rob Ants
Rob Ants

Reputation: 29

Prolog: Assign a list of characters to a list of numbers

I'm working on comparing two lists in parallel to eachother. I want to assign each letter of a list of letters (making up one word) to a list on numbers. So the code I've written so far is simply splitting atoms up into a list.

split( '', [] ).
split(W,X)
    :- atom_chars(W,X).
main
    :- split(listen,X),
       write(X).

and then again with a number split(321645,X) Then the part I don't know how to code properly But assigning each letter, once split up with the number in the same position in the list as it. If I can visualize

[ l , i , s , t , e , n ]
  ^   ^   ^   ^   ^   ^
  |   |   |   |   |   |
[ 3 , 2 , 1 , 6 , 4 , 5 ]

I hope that makes sense. Thanks

Upvotes: 1

Views: 247

Answers (2)

gusbro
gusbro

Reputation: 22585

You may use maplist/3 to apply a goal to each item in both lists and gather the results in another list. Similarly you can use maplist/2 to print the mappings:

assign_map(A, B, LM):-
  split(A, LA),
  split(B, LB),
  maplist(map, LA, LB, LM).
  
map(A,B, A->B).

And the test query:

?- assign_map(listen, 321645, LMap), maplist(writeln, LMap).
l->3
i->2
s->1
t->6
e->4
n->5
LMap = [(l->'3'),  (i->'2'),  (s->'1'),  (t->'6'),  (e->'4'),  (n->'5')].

Upvotes: 2

Reema Q Khan
Reema Q Khan

Reputation: 878

My attempt after what I have understood from your question:-

split( '', [] ).
split(W,X):- atom_chars(W,X).

assignNum(A,B):-
    split(A,LA),
    split(B,LB),
    splitNum(LA,LB).

splitNum([H|T],[H2|T2]):-
        write(H),
        write('->'),
        writeln(H2),
      splitNum(T,T2).

?-assignNum(listen,123456).
l->1
i->2
s->3
t->4
e->5
n->6
false

?-assignNum(award,16548).
a->1
w->6
a->5
r->4
d->8
false

Upvotes: 1

Related Questions