Skip to content

Robot Name

Give each robot off the factory floor a random name of two uppercase letters and three digits, give it a new one when it is reset, and never give two robots the same name.

Adapted from Exercism’s problem specification (MIT). Listed under Games & Simulation.

// FILE: robot_name.nomi
//# Robots with random, unique names such as `RX837`.

import std::random.{Generator, Seed}

once letters = Iter.to_vector('A'..='Z')

/// How many names there are: two letters, then three digits.
once name_count = 26 * 26 * 1000

/// A robot and the name it answers to.
pub opaque struct Robot
    name: String
end

impl Robot
    /// The robot's name: two uppercase letters and three digits, as `RX837`.
    pub fn name(robot: Robot) -> String
        robot.name
    end
end

/// Why the factory cannot name another robot.
pub enum Error
    NamesExhausted
end

/// A factory that names robots at random and never gives two the same
/// name. It is a value: each robot it builds or resets answers the factory
/// after it, holding every name given so far and the seed to draw from next.
pub opaque struct Factory
    seed:  Seed
    given: Set<String>
end

impl Factory
    /// A factory that draws names from `seed`.
    pub fn new(seed: Seed) -> Factory
        {seed:, given: []}
    end

    /// A new robot with a name no robot of this factory has had, or
    /// `NamesExhausted` when every name has been given.
    pub fn build(factory: Factory) -> Result<(Robot, Factory), Error>
        if Set.size(factory.given) == name_count then return Err(.NamesExhausted)

        (name, seed) = Generator.step(names(), factory.seed)

        if name in factory.given then
            Factory.build({..factory, seed:})
        else
            Ok((Robot{name:}, Factory{seed:, given: Set.insert(factory.given, name)}))
        end
    end

    /// `robot` reset to its factory settings: wiped, and named again with a
    /// name no robot of this factory has had. The old name is not given
    /// again.
    pub fn reset(factory: Factory, _robot: Robot) -> Result<(Robot, Factory), Error>
        Factory.build(factory)
    end
end

/// Every name, each equally likely: a number below `name_count`, 676,000, read as two
/// letters and three digits.
fn names() -> Generator<String>
    Generator.int(0..676_000)
    |> Generator.map(fn n ->
        first = Vector.get(letters, n / 26_000)!
        second = Vector.get(letters, n / 1000 % 26)!
        digits = Int.to_string(n % 1000) |> String.pad_start(3, "0")
        String.from_codepoints([first, second]) + digits
    end)
end

// FILE: robot_name_test.nomi
import
    std::random.Seed
    robot_name.{Factory, Robot}
end

/// Whether `name` is two uppercase letters and three digits.
fn is_well_formed(name: String) -> Bool
    case String.to_codepoints(name)
        [a, b, c, d, e] ->
            Iter.all_match([a, b], &(&1 in 'A'..='Z'))
                and Iter.all_match([c, d, e], Codepoint.is_digit)

        _ ->
            False
    end
end

/// The names of `count` robots from `factory`, in the order it built them.
fn names(factory: Factory, count: Int) -> List<String>
    (_factory, names) =
        1..=count
        |> Iter.map_reduce(factory, fn factory, _n ->
            (robot, next) = Factory.build(factory)!
            (next, Robot.name(robot))
        end)

    names
end

group "robot name"
    setup Seed.from_int(42) |> Factory.new()

    test "has a name", factory
        assert Ok((robot, _factory)) = Factory.build(factory)
        assert is_well_formed(Robot.name(robot))
    end

    test "name is the same each time", factory
        assert Ok((robot, _factory)) = Factory.build(factory)
        assert Robot.name(robot) == Robot.name(robot)
    end

    test "different robots have different names", factory
        assert Ok((first, factory)) = Factory.build(factory)
        assert Ok((second, _factory)) = Factory.build(factory)
        assert Robot.name(first) != Robot.name(second)
    end

    test "reset changes the name to a new well-formed one", factory
        assert Ok((robot, factory)) = Factory.build(factory)
        assert Ok((reset, _factory)) = Factory.reset(factory, robot)
        assert Robot.name(reset) != Robot.name(robot)
        assert is_well_formed(Robot.name(reset))
    end

    test "a thousand robots all have different names", factory
        assert names(factory, 1000) |> Iter.to_set() |> Set.size() == 1000
    end

    test "the same seed names the same robots", factory
        again = Seed.from_int(42) |> Factory.new()
        assert names(factory, 5) == names(again, 5)
    end
end
  • Adapted: the exercise asks for a robot object that names itself on first use and whose name a reset wipes in place, with uniqueness kept across every robot in the program. Nomi values do not change and there is no global state, so a Factory value holds what the exercise keeps hidden: the names given so far and the random seed. Factory.build answers a robot and the factory after it, and Factory.reset answers the robot named afresh and the factory after it. A robot is a value whose name never changes, so “the name is the same each time” holds by construction. The exercise has no canonical data, so the tests are the instructions’ rules.
  • Randomness is std/random’s: a Seed threaded through Generator.step. The tests make the factory from a fixed seed, Seed.from_int(42), so they are deterministic, and check properties (the format, different names, a thousand distinct names, the same seed giving the same names) rather than particular names.
  • A name is one draw, Generator.int below 676,000 (26 × 26 × 1000), read as two letters and three digits, so every name is equally likely with no retry inside a name.
  • A drawn name the factory has given before is drawn again. Once all 676,000 names are given, build answers Error.NamesExhausted rather than looping. A reset never gives back the robot’s old name, nor any name given before, so reset needs only the factory; it takes the robot to say which one is reset.
  • The tests are a group whose setup makes the factory, one test per rule. names builds many robots with Iter.map_reduce over the factory; a factory that runs out within a thousand robots would be a bug, so it unwraps each build with !, whose trap would show NamesExhausted.