Gettext.Plural behaviour

Behaviour and default implementation for finding plural forms in given locales.

This module both defines the Gettext.Plural behaviour and provides a default implementation for it.

Plural forms

For a given language, there is a grammatical rule on how to change words depending on the number qualifying the word. Different languages can have different rules. [source]

Such grammatical rules define a number of plural forms. For example, English has two plural forms: one for when there is just one element (the singular) and another one for when there are zero or more than one elements (the plural). There are languages which only have one plural form and there are languages which have more than two.

In GNU Gettext (and in Gettext for Elixir), plural forms are represented by increasing 0-indexed integers. In English, 0 means singular and 1 means plural.

The goal of this module is to, given a locale, determine:

  • how many plural forms exist in that locale (nplurals/1);
  • to what plural form a given number of elements belongs to in that locale (plural/2).

Default implementation

Gettext.Plural provides a default implementation of a plural module. Most languages used on Earth should be covered by this default implementation. If a language isn’t in this implementation, a different plural module can be provided when Gettext is used. For example, pluralization rules for the Elvish language could be added as follows:

defmodule MyApp.Plural do
  @behaviour Gettext.Plural

  def nplurals("elv"), do: 3

  def plural("elv", 0), do: 0
  def plural("elv", 1), do: 1
  def plural("elv", _), do: 2
end

defmodule MyApp.Gettext do
  use Gettext, otp_app: :my_app, plural_forms: MyApp.Plural
end

The mathematical expressions used in this module to determine the plural form of a given number of elements are taken from this page as well as from Mozilla’s guide on “Localization and plurals”.

Examples

An example of the plural form of a given number of elements in the Polish language:

iex> Plural.plural("pl", 1)
0
iex> Plural.plural("pl", 2)
1
iex> Plural.plural("pl", 5)
2
iex> Plural.plural("pl", 112)
2

As expected, nplurals/1 returns the possible number of plural forms:

iex> Plural.nplurals("pl")
3

Summary

Callbacks

Returns the number of possible plural forms in the given locale

Returns the plural form in the given locale for the given count of elements

Functions

nplurals(locale)
plural(locale, count)

Callbacks

nplurals(locale)

Specs

nplurals(locale :: String.t) :: non_neg_integer

Returns the number of possible plural forms in the given locale.

plural(locale, count)

Specs

plural(locale :: String.t, count :: non_neg_integer) :: plural_form :: non_neg_integer

Returns the plural form in the given locale for the given count of elements.