Assignment#5: Functions and Grammars


In Lab , you executed JavaScript code that generated random sequences of characters, some of which turned out to be words. In this assignment, you will take the next step of generating random sentences based on grammar rules. To accomplish this, you will write simple functions that call library functions and each other, and so build complexity out of simplicity.


Random Parts of Speech

Consider the following JavaScript function:

function noun() // Assumes: nothing // Returns: a random noun { return RandomOneOf(["man", "woman", "ball"]); }

This function uses RandomOneOf to select at random from a list of three nouns. The call noun() will thus return one of the three nouns each time it is executed.


EXERCISE 1:    Create a Web page named grammar.html and enter the noun function definition in the HEAD of that page. In the BODY of the page, place a text area and a button of the following form (where outputArea is the name of the text area):

<input type="button" value="Noun" onclick="document.getElementById('outputArea').value = noun();" />

Click the button 10 times and list the displayed values below:










EXERCISE 2:    Similar to the noun function above, define additional functions called verb and article that return a random verb (e.g., "hit", "liked", "smelled") and article (e.g., "the", "a", "some"), respectively. Feel free to add to the vocabulary of these functions. Add buttons corresponding to each of your new functions.

Important: Each function should return its randomly generated word, NOT directly display it in the text area!





Grammar Rules

If you recall from your grade school days, sentences can be parsed according to grammar rules - syntactic rules that specify how the different parts of speech can fit together. For example, a simple sentence can be constructed with an article, followed by a noun, followed by a verb, such as "The ball smelled." or "Some woman hit." This can be written as a grammar rule in the following notation:

sentence <--- article + noun + verb



EXERCISE 3:    Define a function called sentence that returns a sentence of the above form. Your function should have no inputs (similar to noun, article, and verb), and should work by calling each of the previously defined functions and concatenating the resulting words with spaces in between. Note that the format of a sentence is not random, it will always consist of an adjective followed by a noun followed by a verb. The random appearance of sentences is due to the fact that the individual words are randomly generated by the other functions.

Important: Your function should return the sentence, NOT directly display it in the text area!

Once you have defined your function, add a corresponding button to the body of the page that calls the sentence function and displays the returned sentence in the text area. Click the button 10 times and list the displayed sentences below: