In an earlier post, I showed how Prolog can be used to generate poetry, making use of my “iLexicon”. I want to continue the discussion today by giving another example, this time based on the theme of sounds emitted by various animals and birds.
As hinted in my previous articles, “iLexicon” stands for “Intelligent Lexicon”. It is a fairly large repository (presently containing around 2.5 million entries) of English words and their related information. In this article, I showed how “iLexicon” can help us in identifying interesting word patterns. That example was based on the Lisp implementation of iLexicon; subsequently I have also ported it to Sicstus prolog.
In today’s article, I will walk you through a DCG (Definite Clause Grammar) that generates a poem referencing various sounds of animals and birds. In order to do this, it taps into the knowledgebase contained in iLexicon about various species (animals, birds, fish, insects, etc.) and the names of sounds emitted by them. For example,
- a “frog” “croaks”
- a “donkey” “brays”
- a “kangaroo” “chortles”
- etc.
The DCG attempts to build a poem by stringing together a few of these <entity, sound> combinations. Just to make the poem interesting, it optionally defines a starting catchphrase and an ending catchphrase.
The following shows the setup and the DCG:
The generation logic is embodied in the following code (same as the one in the earlier article).
As the first example, let us generate a few lines using only animal sounds:
While generating each line, an animal is selected at random from the KB and its corresponding sound is paired. In case an animal sound has multiple names, one of those is again selected at random.
I did not bother to indent the lines to make the presentation attractive. Also, the “Yes” at the end is the value printed by the Prolog interpreter to indicate whether the predicate succeeded or failed; it is not part of the poem.
What happens if we run the generator again? The result is likely to be different because of the randomness:
Of course, we retain the first and last line without any change.
For our second example, let us focus on birds:
Here is another run:
Note again that the two results are different.
For the last example, let us choose between animal and bird randomly!
Let us try again:
Notice how the DCG rule “random_sound” chooses between “animal_sound” and “bird_sound”.
That was simple, wasn’t it? What makes this possible is the extensive information available in “iLexicon” coupled with the succinct generation formalism of DCG in Prolog.
Hope you liked this article. I will continue to share more interesting ideas in future articles. Have a great weekend!
Recent Comments