Skip to content

Secret Handshake

Turn a number’s lowest five bits into the actions of a secret handshake, reversed when the fifth bit is set.

Adapted from Exercism’s problem specification (MIT). Listed under Numbers & Math.

// FILE: secret_handshake.nomi
//# The secret handshake a number's lowest five bits spell.

once reverse_bit = 16

/// An action of the handshake, in the order the bits list them.
pub enum Action
    Wink
    DoubleBlink
    CloseYourEyes
    Jump
end

derive Variants for Action

/// The actions `number`'s bits ask for: one per set bit from 1 to 8, in that
/// order, reversed when bit 16 is set too. Higher bits are ignored.
pub fn commands(number: Int) -> List<Action>
    actions =
        Action.variants()
        |> Iter.filter(fn action -> is_set(number, bit(action)))
        |> Iter.to_list()

    if is_set(number, reverse_bit) then Iter.reverse(actions) else actions
end

fn bit(action: Action) -> Int
    case action
        .Wink          -> 1
        .DoubleBlink   -> 2
        .CloseYourEyes -> 4
        .Jump          -> 8
    end
end

fn is_set(number: Int, bit: Int) -> Bool
    number &&& bit != 0
end

// FILE: secret_handshake_test.nomi
import secret_handshake.{self, Action}

test "commands"
    [
        ("wink for 1", 1, [Action.Wink]),
        ("double blink for 10", 2, [.DoubleBlink]),
        ("close your eyes for 100", 4, [.CloseYourEyes]),
        ("jump for 1000", 8, [.Jump]),
        ("combine two actions", 3, [.Wink, .DoubleBlink]),
        ("reverse two actions", 19, [.DoubleBlink, .Wink]),
        ("reversing one action gives the same action", 24, [.Jump]),
        ("reversing no actions still gives no actions", 16, []),
        ("all possible actions", 15, [.Wink, .DoubleBlink, .CloseYourEyes, .Jump]),
        ("reverse all possible actions", 31, [.Jump, .CloseYourEyes, .DoubleBlink, .Wink]),
        ("do nothing for zero", 0, []),
    ]
    |> subtests (description, number, expected), description
        assert secret_handshake.commands(number) == expected
    end
end
  • Actions are an Action enum with derive Variants, so Action.variants() lists them in bit order, and the canonical strings become variants in the tests.
  • Each action’s bit is spelled out in a case (bit), as allergies does, rather than computed from the action’s position.
  • The reverse flag is a once reverse_bit = 16, tested by the same is_set helper as the actions.
  • The filter is fn action -> is_set(number, bit(action)) rather than the capture &is_set(number, bit(&1)): the body is two calls, which read better with a named parameter.
  • The table qualifies only its first row’s action ([Action.Wink]); the later rows’ bare variants, and the empty lists, take that enum.