'How can i set a newline in a set string in SWI-Prolog?

I have this string:

B='Dogs cats birds and fish'.

and i need it to appear in the format bellow:

Dogs,
cats,
birds,
and fish

Is there any possible way for this to happen?

I tried nlas in: B='Dogs,nl, cats,nl, birds,nl, and fish'.

and \n as in: B='Dogs,\n, cats,\n, birds,\n, and fish'.

to no avail

B='Dogs cats birds and fish'.



Solution 1:[1]

The new line character works, you should use write/1 [swi-doc] to print the string to the console, like:

?- write('Dogs,\ncats,\nbirds,\nand fish').
Dogs,
cats,
birds,
and fish
true.

?- B = 'Dogs,\ncats,\nbirds,\nand fish', write(B).
Dogs,
cats,
birds,
and fish
B = 'Dogs,\ncats,\nbirds,\nand fish'.

If you unify a variable, the Prolog will print that variable as a string literal, not the content of the string.

Solution 2:[2]

you should split the string as a list, and then iterate the list and write.

In Prolog, nl is a Predicate, is can not be used like \n,

print_s([]).
print_s([H|L]):-
    write(H),
    nl,
    print_s(L).

print_s(['Dogs,', 'cats,', 'birds', 'and fish']).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 H.Wang