Search code examples
listprologappendcallpredicate

How to call a predicate that appends two lists in Prolog?


Everywhere I look I see something like this: append([1,2,3],[a,b,c],appended)., but what if I have 2 lists : ok([1,2,3]). and hello([a,b,c]). and I want to append ok and hello together.

Why does append(ok,hello,appended). not work?

How would I do it that way without having to manually type in every element if the lists are already defined?


Solution

  • You first query the lists, then append them:

    ok( OK), hello( Hello), append( OK, Hello, Appended).
    

    Prolog's logical variables names must start with Upper Case letters.

    If you want to see only Appended reported as the result of your query, try

    ok( _OK), hello( _Hello), append( _OK, _Hello, Appended).
    

    Another, less hackish way to accomplish this, as suggested in the comments by Enigmativity, is to define a special-purpose predicate for that,

    appended( Appended) :-
      ok( OK), hello( Hello), append( OK, Hello, Appended).