Main      Site Guide    
Smash Tutorial

Example: Displaying Pluralized Nouns


Frequently it may be necessary to display an enumerated quantity of items, such as "You have 63 points" or "You see 9 camels." Except for one nagging special case, we could code such a thing quite easily, as follows:

. You are in the desert. You see {camels} camels.

In the example above, the variable "camels" keeps track of how many camels are visible at the moment. It works, unless the variable "camels" ever becomes one, in which situation the user would see the slovenly string, "You see 1 camels."

To handle the possibility of a singular number of camels, we must adjust the code as such:

c camels = 1 . You are in the desert. You see 1 camel. C . You are in the desert. You see {camels} camels.

This is tedious. Ideally, there should be a way to accomplish this effect with less code. Clever coders might devise the following solution, which uses string encoding:

. You are in the desert. You see {camels} camel{'(camels != 1) * c:s}.

If you work it out in your head, you'll find that when "camels" is 1, the expression in {'...} evaluates to 0, which produces an empty string for output. However, when "camels" is something other than 1, the expression evaluates to c:s, which, inside {'...}, displays an "s" character.

While this code works just fine, Smash provides a simpler way to accomplish the same thing with the p: and P: operators. Here is the same code, rewritten to make use of the p: operator:

. You are in the desert. You see {camels} camel{'p:camels * c:s}.

The p: operator returns 0 if its argument is singular, and 1 if it's plural. By multipling that with an encoded "s," the desired effect is achieved. But the P: operator makes it easier still:

. You are in the desert. You see {camels} camel{'P:camels}.

The P: operator returns 0 if its argument is singular, and an encoded "s" character if it's plural. This makes pluralizing regular nouns nice and compact. You may still need to use p: if pluralizing a noun involves adding other characters, however:

. You are in the meadow. You see {foxes} fox{'p:foxes * c:es}.

There are still situations that require some triflingly complex code to pluralize certain nouns. Here, for example, is the code you need for "bunnies":

. You are in the meadow. You see {bunnies} bunn{'(p:bunnies * c:ies) + (!p:bunnies * c:y)}.

That code works, but you may feel more comfortable simply using conditionals and printing out one of two separate lines. Either way works fine.