lango

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 10 Imported by: 0

README

lango

Go package github.com/maloquacious/lango: generates names in invented languages. A port of Martin O'Leary's language.js. The package documentation (go doc -all github.com/maloquacious/lango) is the specification: the algorithm, every Spec field with its default, the errors, and where the port departs from the source.

rng := rand.New(rand.NewPCG(1, 1))
lang, err := lango.New(lango.RandomSpec(rng), rng)
if err != nil {
	return err
}
name, err := lang.Name("city")

Six names from seed 1, keys city ×3 then river ×3 (from Example in example_test.go):

city Ushtaz
city Niz Míshkázh
city Kázhízh
river Kázkízhás
river Sizashmízh
river Ash Mís

Output is deterministic: the same Spec, the same random stream, and the same sequence of calls give the same names. All randomness comes from the *rand.Rand passed to New and RandomSpec. Each call advances that stream and grows the language's morpheme and word pools, so changing the order of calls changes every later name. A Language made with New is not safe for concurrent use; one made with NewSync is, but then which goroutine gets which name depends on scheduling. Output does not match language.js for any seed.

Stability: until v1.0.0, a minor release may change the names a given seed produces; a patch release will not. If you store seeds, pin the module version.

Checks: go vet ./... and go test ./....

Licence: MIT; see LICENSE.

Documentation

Overview

Package lango generates names in invented languages.

It is a Go port of Martin O'Leary's language.js (MIT licence), the copy bundled with ProcGenesis WorldGen.

Use

Build a Spec, make a Language from it with New, and ask the Language for names:

rng := rand.New(rand.NewPCG(seed, seed))
lang, err := lango.New(lango.RandomSpec(rng), rng)
name, err := lang.Name("city")

RandomSpec draws a whole language (sound inventory, syllable shape, spelling) from the random stream. BasicSpec is a fixed minimal language.

How a name is built

  • A syllable fills each class letter of Spec.Structure with a phoneme of that class. A letter followed by '?' is left out with probability 0.5. Phoneme i of a class of n is chosen with probability weighted by Spec.Exponent: index = floor(u^Exponent × n), u uniform in [0, 1), so earlier phonemes are more frequent when Exponent > 1. A syllable that breaks one of Spec.Restrictions is drawn again. It is then spelled (see Spec.Spell).
  • A morpheme is a syllable kept in a pool per key. With Spec.Morphemes set, Language.Morpheme returns a pooled morpheme with probability len(pool)/(len(pool)+e), where e is 10 for the empty key and 1 otherwise, and a new syllable otherwise. A new syllable that is already in the pool of any key is drawn again.
  • A word is MinSyllables to MaxSyllables morphemes, uniformly; one of them, chosen uniformly, is drawn under the word's key and the rest under the empty key. Words are pooled per key the same way, with e equal to 3 for the empty key and 2 otherwise.
  • A name is, with probability 0.5, one capitalised word; otherwise two distinct capitalised words, each under the name's key with probability 0.6 (else the empty key), joined by Spec.Joiner, directly with probability 0.5 and otherwise with the language's genitive morpheme (key "of") between them. With probability 0.1 the definite morpheme (key "the") is put in front. A name whose length in runes is outside [MinLength, MaxLength], or that contains or is contained in a name already given, is drawn again.

Keys are free text. Names under one key share morphemes and words, which is what makes, say, all river names sound alike.

Determinism

All randomness comes from the *rand.Rand passed to New and RandomSpec. The same Spec, the same random stream, and the same sequence of calls give the same names.

Stability of names

Until v1.0.0, a minor release (v0.x.0) may change the names a given seed produces; a patch release (v0.x.y) will not. Pin the module version if you store seeds and need the same names back.

Concurrency

A Language made with New is not safe for concurrent use. One made with NewSync is: each call holds a lock, so goroutines take turns and names stay distinct across all of them. Concurrent use is not deterministic, because the order in which goroutines get the lock decides which call gets which draws from the random stream.

Departures from language.js

  • Every loop that draws again gives up after 10,000 attempts and returns ErrExhausted. The source loops forever, which happens once a small language has used up its names.
  • Phoneme lists are shuffled with a uniform Fisher–Yates shuffle. The source's shuffle never leaves an element in place (Sattolo's algorithm), which looks unintended.
  • Restrictions are named rules (Restriction) instead of regular expressions; the three are those of the source's "Doubles and hard clusters" set, which is the only one the source uses.
  • Name length is counted in runes, not UTF-16 code units. All phonemes and spellings in this package are single code units, so the counts agree.
  • The source's unused "nowordpool" flag is dropped.
  • Output is not compatible with the source for any seed.
Example
package main

import (
	"fmt"
	"math/rand/v2"

	"github.com/maloquacious/lango"
)

func main() {
	rng := rand.New(rand.NewPCG(1, 1))
	lang, err := lango.New(lango.RandomSpec(rng), rng)
	if err != nil {
		panic(err)
	}
	for _, key := range []string{"city", "city", "city", "river", "river", "river"} {
		name, err := lang.Name(key)
		if err != nil {
			panic(err)
		}
		fmt.Println(key, name)
	}
}
Output:
city Ushtaz
city Niz Míshkázh
city Kázhízh
river Kázkízhás
river Sizashmízh
river Ash Mís

Index

Examples

Constants

View Source
const (
	// ErrInvalidSpec is returned, wrapped with the name of the field, by
	// [Spec.Validate] and [New].
	ErrInvalidSpec = Error("invalid spec")
	// ErrExhausted is returned when 10,000 attempts in a row fail to
	// produce a new syllable, morpheme, word, or name that meets the
	// Spec's rules. The Language stays usable: later calls may succeed for
	// other keys, but not for the same key.
	ErrExhausted = Error("no new value after 10000 attempts")
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error string

Error is the type of the package's sentinel errors.

func (Error) Error

func (e Error) Error() string

type Language

type Language struct {
	// contains filtered or unexported fields
}

Language makes names from a Spec. Make one with New. It remembers every morpheme, word, and name it has given, so names stay distinct and share parts. A Language made with New is not safe for concurrent use; one made with NewSync is.

func New

func New(spec Spec, rng *rand.Rand) (*Language, error)

New returns a Language for spec that draws from rng. It returns an error wrapping ErrInvalidSpec if spec fails Validate. The Language copies what it needs from spec; changing spec afterwards does not affect it.

func NewSync

func NewSync(spec Spec, rng *rand.Rand) (*Language, error)

NewSync is like New, but the Language it returns is safe for concurrent use. Each call to Syllable, Morpheme, Word, or Name holds a lock for its whole run, so calls from many goroutines take turns and names stay distinct across all of them. Nothing else may use rng while the Language is in use.

The names given are still drawn from the one random stream in call order, but which goroutine's call comes first depends on scheduling, so concurrent use is not deterministic.

func (*Language) Morpheme

func (l *Language) Morpheme(key string) (string, error)

Morpheme returns a morpheme for key: one from key's pool, or a new syllable added to it that is in no key's pool. With Spec.Morphemes false it returns a new syllable and pools nothing.

func (*Language) Name

func (l *Language) Name(key string) (string, error)

Name returns a new name for key. No name the Language has given contains it, and it contains none of them. It returns ErrExhausted when no such name of the allowed length turns up.

func (*Language) Syllable

func (l *Language) Syllable() (string, error)

Syllable returns a new spelled syllable. It is not pooled. It returns ErrExhausted if every attempt breaks a Restriction.

func (*Language) Word

func (l *Language) Word(key string) (string, error)

Word returns a word for key: one from key's pool, or a new word added to it that is in no key's pool. One morpheme of a new word is drawn under key, the others under the empty key.

type Restriction

type Restriction uint8

Restriction is a rule that rejects a syllable. Rules apply to the phonemes, before spelling.

const (
	// NoDoubles rejects the same phoneme twice in a row.
	NoDoubles Restriction = iota + 1
	// NoSibilantClusters rejects s, ʃ, or f followed by s or ʃ.
	NoSibilantClusters
	// NoLiquidClusters rejects r or l followed by r or l.
	NoLiquidClusters
)

type Spec

type Spec struct {
	// Phonemes maps a class letter to its phonemes, one rune each, most
	// likely first. Each key is one rune other than '?'. Every class letter
	// in Structure must have at least one phoneme. BasicSpec:
	// C "ptkmnls", V "aeiou", S "s", F "mn", L "rl".
	Phonemes map[string]string `json:"phonemes"`
	// Structure is the shape of a syllable: a sequence of class letters,
	// each optionally followed by '?' to make it optional (left out with
	// probability 0.5). It must contain at least one class that is not
	// optional. BasicSpec: "CVC".
	Structure string `json:"structure"`
	// Exponent weights the choice of phoneme toward the start of its list:
	// index = floor(u^Exponent × n). Greater than 0; 1 is uniform.
	// BasicSpec: 2.
	Exponent float64 `json:"exponent"`
	// Restrictions are the rules a syllable must not break. Order does not
	// matter. BasicSpec: none.
	Restrictions []Restriction `json:"restrictions"`
	// Spell turns on spelling. When false, a syllable is written as its
	// phonemes. When true, each phoneme is written as the first non-empty
	// value among ConsonantSpelling, VowelSpelling, the default spelling
	// (ʃ sh, ʒ zh, ʧ ch, ʤ j, ŋ ng, j y, x kh, ɣ gh, ʔ ‘, A á, E é, I í,
	// O ó, U ú), and the phoneme itself. BasicSpec: false.
	Spell bool `json:"spell"`
	// ConsonantSpelling maps a phoneme (one rune) to how it is written.
	// BasicSpec: empty.
	ConsonantSpelling map[string]string `json:"consonant_spelling"`
	// VowelSpelling maps a phoneme (one rune) to how it is written.
	// BasicSpec: empty.
	VowelSpelling map[string]string `json:"vowel_spelling"`
	// Morphemes turns on the morpheme pools. When false, every morpheme is
	// a new syllable, so words share no parts. BasicSpec: false.
	Morphemes bool `json:"morphemes"`
	// MinSyllables is the fewest syllables in a word. At least 1.
	// BasicSpec: 1.
	MinSyllables int `json:"min_syllables"`
	// MaxSyllables is the most syllables in a word. At least MinSyllables.
	// BasicSpec: 1.
	MaxSyllables int `json:"max_syllables"`
	// Joiner is put between the words of a name. BasicSpec: " ".
	Joiner string `json:"joiner"`
	// MinLength is the shortest name, in runes, including joiners. At
	// least 0. BasicSpec: 5.
	MinLength int `json:"min_length"`
	// MaxLength is the longest name, in runes, including joiners. At least
	// MinLength and at least 1. BasicSpec: 12.
	MaxLength int `json:"max_length"`
}

Spec describes a language. It is plain data and round-trips through encoding/json. Start from BasicSpec or RandomSpec and change fields.

func BasicSpec

func BasicSpec() Spec

BasicSpec returns a minimal language: CVC syllables of seven consonants and five vowels, one syllable per word, no spelling, no morpheme pools.

func RandomSpec

func RandomSpec(rng *rand.Rand) Spec

RandomSpec returns a language drawn from rng. It starts from BasicSpec, turns on Spell and Morphemes, and draws:

  • each phoneme class C, V, L, S, F from a list of inventories (for example "English-ish" or "Hawaiian-ish" consonants), weighted toward the simpler ones, then shuffled;
  • Structure uniformly from 22 shapes;
  • Restrictions: always all three;
  • consonant spelling (default, Slavic, German, French, pinyin) and vowel spelling (acutes, umlauts, Welsh, diphthongs, doubles), weighted toward the first;
  • MinSyllables 1 or 2, plus 1 when Structure is shorter than three runes; MaxSyllables uniformly from MinSyllables+1 to 6;
  • Joiner " " with probability 0.75, otherwise "-".

Weighted choices use an exponent of 2 (see Spec.Exponent). The result always passes Validate.

func (Spec) Validate

func (s Spec) Validate() error

Validate reports the first field that breaks the rules in its doc comment, as an error wrapping ErrInvalidSpec.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL