Search code examples
prologswi-prolog-for-sharing

Using insert predicate in SWI-Prolog swish?


I'm trying to execute what seems like a simple three lines of code

insert(X,[],[X]).
insert(X,[H|T],Z):-X>=H,Z=[X,H|T].
insert(X,[H|T],Z):-X<H,insert(X,T,Z2),Z=[H|Z2].

but for some reason I can't get it to compile or execute on the many online code compilers out there SWISH, IDEone, etc. It seems the problem is "insert" isn't a recognized predicate. I tried a few google searches and nothing seems to come up for insert. Thanks! (Sorry very new to Prolog)

ERROR: /home/uJ0Y9U/prog:13:
    No permission to modify static procedure `true/0'
Warning: /home/uJ0Y9U/prog:15:
    Goal (directive) failed: user:main
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit

edit: It seems there was an issue with non-ascii characters. That caused an error of ERROR: /home/F3Vzlp/prog:10:21: Syntax error: Operator expected ERROR: /home/F3Vzlp/prog:11:21: Syntax error: Operator expected


Solution

  • Your program works e.g. with http://swish.swi-prolog.org/, swipl, and gprolog. Here is a transcript using the latter:

    $ gprolog --consult-file insert.prolog
    GNU Prolog 1.4.4 (64 bits)
    ...
    insert.prolog compiled, 3 lines read - 1234 bytes written, 16 ms
    | ?- insert(1,[0,2,4], X).
    insert(1,[0,2,4], X).
    
    X = [1,0,2,4] ? ;
    ;
    
    no
    | ?- 
    

    The first error message you encountered (regarding "true/0") suggests that there was some extraneous text somewhere.

    By the way, your program can be improved slightly. (Hint: there's no need for Z.)