Search code examples
prologdcg

Predicate doesn't work "the other way"


This function takes a string and makes it to pirate language.

But it doesn't work when I want it to take pirate language and return the normal language.

  :- dynamic (lang/2).
  lang([],[]).
  lang(Text, Text2) :-
    [Head|Tail] = Text,
    lang(Tail,X2),
    (member(Head,[101,97,105,111,117,121])
        -> append([Head],X2,Text2)
        ; append([Head,111,Head],X2,Text2)
        ).

it works when calling lang([list of hex codes for chars], X). But it doesn't work with lang(X, [answer from above]).


Solution

  • If you use a DCG, which is the right tool for this sort of processing, you can get both directions:

    lang([]) --> [].
    lang([H|T]) --> [H], { member(H, [101, 97, 105, 111, 117, 121]) }, lang(T).
    lang([H,111,H|T]) --> [H], { \+ member(H, [101, 97, 105, 111, 117, 121]) }, lang(T).
    
    lang(Text, Arg) :- phrase(lang(Arg), Text).
    

    Query results:

    | ?- lang("arg", L), atom_codes(A, L).
    
    A = arorgog
    L = [97,114,111,114,103,111,103] ? ;
    
    no
    | ?- lang(A, "arorgog"), atom_codes(L, A).
    
    A = [97,114,103]
    L = arg ? ;
    
    no
    | ?-
    

    I'll leave it as an exercise to tidy it up. :)