Search code examples
listprolog

how to print something inside a list without the '[]' and ',' in Prolog


When user input 'saya suka makan pisang', the expected output is 'i like eat banana'. But now what I'm getting is [i,like,eat,banana]. How should i fix that?

these are my facts:

words(saya,i).
words(makan,eat).
words(pisang,banana).
words(suka,like).

translation(X,Y):-
    words(X,Y).
translation(X,Y):-
    words(Y,X).
translation(X,X).

translate([], []).
translate([H|T], [H1|T1]):-
             translation(H, H1),
             translate(T,T1).

prolist([],[]).
prolist(SL,[W|T]):-
    split(SL,WL,R),
    name(W,WL),
    prolist(R,T).

split([],[],[]).
split([32|T],[],T).
split([H|T],[H|T2],R):-
    split(T,T2,R).  

run:-
    nl,write('Enter One sentence or word (English or Malay):'),
    read(X),end(X),
    nl.

end(X):-    
    X=q->write('SESSION END. THANK YOU. ');
    name(X,SL),prolist(SL,List),translate(List,W),
    nl,
    write('Translated as:'),
    write(W),
    nl,
    run.

Solution

  • List elements in Prolog are always seperated via ',' and to signalize that they are lists they are wrapped with "[List]"

    However you can convert your List to an atom and remove your brackets and ',' by using in your case:

    atomic_list_concat(List, ' ', W)

    List is the List you are using, ' ' is the seperator you want, in this case you dont want any, and W is the output atom you will get for this predicate. The predicate and its parameters are:

    atomic_list_concat(+List, +Separator, -Atom)

    All you have to do is to replace your end(X) predicate with

    end(X):-    
    X=q->write('SESSION END. THANK YOU. ');
    name(X,SL),prolist(SL,List),translate(List,K), atomic_list_concat(K, ' ', W),
    nl,
    write('Translated as:'),
    write(W),
    nl,
    run.
    

    and it will work as intended

    for more look up: http://www.swi-prolog.org/pldoc/man?predicate=atomic_list_concat/3