简体   繁体   中英

Print list of lists, Prolog

I got this grid:

tab([[s,f,f,f,s,f,f,f,s],
     [f,s,f,f,f,f,f,s,f],
     [f,f,s,f,f,f,s,f,f],
     [f,f,f,f,f,f,f,f,f],
     [s,f,f,f,m,f,f,f,s],
     [f,f,f,f,f,f,f,f,f],
     [f,f,s,f,f,f,s,f,f],
     [f,s,f,f,f,f,f,s,f],
     [s,f,f,f,s,f,f,f,s]]).

I want to print in the screen without brackets and commas. By the way I can't print it right with or without them.

These are the print rules:

viewTab([]).
viewTab([H|T]) :-
    printList(H),
    viewTab(T).

printList([]) :-
    nl.
printList([H|T]) :-
    write(H),
    write(' | '),
    printList(T).

I call it in the Prolog's terminal like:

?- viewTab(X), tab(X).

I can't print a thing, and I get an infinite loop at:

printList([]) :-
   nl.

Can you help me find my mistake?

Or some tips to make the code easier to work with.

Your viewTab/1 is not a purely logical predicate: it has a side effect, and it does not terminate for if its argument is a variable.

For example:

?- listing(foo).

foo([]).
foo([_|A]) :-
    foo(A).

true.

?- foo(X).
X = [] ;
X = [_G256] ;
X = [_G256, _G259] ;
X = [_G256, _G259, _G262] ;
X = [_G256, _G259, _G262, _G265] ;
X = [_G256, _G259, _G262, _G265, _G268] . % and so on

So this:

?- viewTab(X), tab(X).

Puts a list in X , then tab(X) fails, and you are back at viewTab(X) , ad infinitum.

You should try:

?- tab(X), viewTab(X).

Use !

Definite clause grammars are a versatile, logical way of processing input/output.

For a start, read this well-written DCG primer by Markus Triska, also known as @mat on SO !


Right now, as a quick fix, use the built-in predicate format/2 like this:

?- X = [a,b,c], format('~s~n',[X]).
abc                                    % output via side-effect
X = [a, b, c].                         % query succeeds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM