user13
user13

Reputation: 87

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'.

Upvotes: 7

Views: 12015

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476740

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.

Upvotes: 3

H.Wang
H.Wang

Reputation: 41

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']).

Upvotes: 3

Related Questions