Tuesday, March 12, 2019

Writing a list as a sentence in prolog

Or how to process a list using "Head" and "Tail" split with recursion.

In prolog language, "write()" is the way to print an item to the console. As an example, you can do:

  write("Hello World!\n").
to display the "Hello World!" with a new line.
However, it get really old when you want to "write" a mix of variables and strings to display your result. Imagine you have the variable Name = "Rei", and you want to print "Hello, Rei". You need to do
  write("Hello "),write(Name),write("."),nl
to get
  Hello Rei.
The more variables and text mashup you have the more tedious it becomes.

One way to address this problem is to write your own function to write out a list. For example given the following list:

  ["Hello", Name]
  where Name is a prolog variable which contains "Rei"
Your function - let's call it "writelist/1" with the ["Hello",Name] as its argument should print an output as above.

One way to implement it is as follow:

writelist([H]) :- write(H),write("."),nl.
writelist([H|T]) :- write(H),write(" "),writelist(T).
This is very simple and very descriptive. You should try it.

Note

I am using "SWI Prolog" to write Prolog program. I also use Prolog for a living too. :)

No comments:

Post a Comment