Skip to content

Language reference

This page gives an overview of the built-in types and functions in nkl.

Core concepts

Signal

typeSignal[A]

Means a discrete time function with value A at all times

functionSignal.map(s: Signal[A], f: A -> B) -> Signal[B]

Functor. Pointwise application of a function f to the output of e.

functionSignal.merge(items: (…Signal[X_i],…), f: Tuple[…X_i,…] -> Z) -> Signal[Z]

Variadic Applicative. Joins many upstream items to one output signal, using f.

functionSignal.snapshot(signals: (…Signal[X_i],…), when: Event[B], f: Tuple[…X_i,…, B] -> C) -> Event[C]

Mainly used to read time and other signals

typeEvent[A]

Means an ordered list of occurrences and their times List[Tuple[Time, A]].

functionEvent.map(e: Event[A], f: A->B) -> Event[B]
functionEvent.merge(items: (…Event[X_i],…), f: Tuple[…Option[X_i],…] -> Z) -> Event[Z]
functionEvent.filter(e: Event[A], f: (A -> Boolean)) -> Event[A]

When receiving an occurrence, skips updating its output when the filter is False. Can be used to define when an Interaction ends.

functionEvent.hold(e: Event[A], initial: A) -> Signal[A]
functionEvent.reduce(e: Event[A], f: (A, S) -> S, initial: S) -> Event[S]

Creates an event stream whenever the event e occurs. This can be used to write Elm-like patterns.

Interactions

typeOp[A]

Describes an operation that can be evaluated by the host environment in the current scope. It returns a value of type A when bound in a do block.

typeStimulus
typeStimulus.static(f: Location -> Color) -> Stimulus

This is equivalent in meaning to a static Signal[Location->Color]

typeStimulus.dynamic(signals: (…Signal[X_i],…), render: Tuple[…X_i,…] -> (Location -> Color)) -> Stimulus

This is equivalent in meaning to a Signal[Location -> Color]; here it might have dependencies on time and agent inputs

Useful for the elm pattern

functionStimulus.stack(stimulus: Stimulus, items: List[Stimulus]) -> Stimulus

Lifted Color.stack

functionStimulus.blend(stimulus1: Stimulus, stimulus2: Stimulus, t: Between[Float, 0, 1]) -> Stimulus

Lifted Color.blend

functioninteraction(show: Stimulus, until: Event[A]) -> Op[A]

Describes an interaction between the world and the program. It shows the picture show describes at each time on the display, until the next occurrence of until, and returns that occurrence's value, which is typed R.

Sequencing

statementasync def {name}(...): ...

async def blocks are do-like blocks which start their own timers and event streams. await statements are the only ones which may advance logical time. Execution proceeds line-by-line, and it is time t=0 until an await call occurs, after which it is some time t >= 0. They create their own new scopes, as an interaction does; they are themselves functions with an Op-typed return.

statementdef {name}(...): ...

Describes a pure function

expressionlambda {names,...}: ...

Describes a pure function

statement{name} = {expression}

let statement.

statementawait {op: Op[A]}

This evaluates to a value with type A. The meaning is bind(op, lambda name: rest).

Law: No input is seen twice or skipped: the next interaction picks up occurrences after the previous one ended.

statementreturn {value}

A def that ends without a return statement has a return type of None.

Example syntax:

python
import nkl 

@nkl.function
async def hello() -> Boolean: 
  ...
  my_interaction = interaction(show=..., until=...) # Op[Boolean]
  x = await my_interaction # Boolean
  return x


hello # () -> Op[Boolean]
hello() # Op[Boolean]

Time

typeTime <: Integer

An offset of time with respect to an origin; here interaction start. Microseconds

Events are admitted in order of their Time, which never decreases: an input that happened before a timer fired comes before it.

aliasDuration = Positive[Integer]
functiontime.now() -> Op[Time]

Returns the host-read physical time.

functiontime.signal() -> Signal[Time]

A Signal of the host-read physical time; these are frame times (relative to the interaction start epoch, as usual). When snapshotted, note the snapshot-causing Event admission carries its own physical time.

functiontime.elapsed(duration: Duration) -> Event[Time]

Schedules a timer event that fires when at least duration time has elapsed in physical time. Ideally, the timer fires on time; in practice, it may fire late. The resolving Event admission reports the physical time (clock microsecond) it fired on.

functiontime.tick(every: Duration, offset: Time=0) -> Event[Time]

Schedules tick events that fires at most every every; the normative host admits a timer event whenever (t-offset) // every changes, starting at 1. However, the host provides no guarantees other than the accuracy of the time payload of events defined by this channel, and never triggering this more frequently than every.

Useful for driving physics simulations, and for throttling graphics which are defined as updating at discrete points in time.

python

def evolve_state(num_steps: Float, state: MyState, ) -> MyState: 
  # See this blogpost by Glenn Fiedler [Fix Your Timestep](https://gafferongames.com/post/fix_your_timestep/).
  # `num_steps` counts from the interaction start, so `state` keeps the steps it has taken and takes the rest.
  ...


def render(state: MyState) -> Spatial[Color]: 
  ...

def is_terminal_state(state: MyState) -> Boolean: 
  ...

def state_summary(state: MyState) -> MyInteractionOutput: 
  ...

@nkl.function
async def my_physics(initial_state: MyState) -> MyInteractionOutput: 

  dt = 10_000 # physical steps of 10 milliseconds
  ticks = nkl.time.tick(every=dt) # Event[Time]
  steps = ticks.map(lambda t: t / dt) # Event[Float]; the number of steps that have elapsed since the interaction start; Float lets us perform interpolation if so-desired

  state_updated_event = steps.reduce(
    f=evolve_state, 
    initial=initial_state,
  ) # Event[MyState]

  signal = state_updated_event.hold(
    initial=initial_state
  ) # Signal[MyState]

  graphics = Stimulus.dynamic(
    (signal,),
    render,
  ) # Stimulus

  done = state_updated_event.filter(
    f=is_terminal_state
  ).map(state_summary)

  result = await interaction(show=graphics, until=done)

  return result

Inputs

Pointer

functionpointer.now(): Op[PointerState]
functionpointer.state(): Signal[PointerState]

initial state given by host

functionpointer.inputs(): Event[PointerInput]
typePointerState = Record[location: Location, down: Boolean, connected: Boolean]
typePointerInput = Enum[Move: Location, Down: Nothing, Up: Nothing, Connect: PointerState, Disconnect: Nothing]

Keyboard

functionkeyboard.now(): Op[KeyboardState]
functionkeyboard.state(): Signal[KeyboardState]

The state of the given key at every time. The initial value is given by the host.

functionkeyboard.inputs(): Event[KeyboardInput]
valuekeyboard.translated(): Event[Keyboard.TranslatedInput]

Law: always admitted after the KeyboardInput Implementation law: in the trace, the host admits a Keyboard.TranslatedInput only right after the press it translates.

typeKeyboardState = Record[down: Set[Keyboard.Key]]
typeKeyboardInput = Enum[Press: Keyboard.Key, Release: Keyboard.Key, Connect: KeyboardState, Disconnect: Nothing]

What a press of Keyboard.events means by the host's keyboard layout: an occurrence for each press the layout translates, at its time and after it.

The layout is the host's: a state S, opaque to a program, and a function (S, Keyboard.Input) -> (S, Option[Keyboard.TranslatedInput]) that takes the state through every Keyboard.Input and gives each press its translation. The state is how Shift, Caps Lock, or a dead key changes what a later press means.

typeKeyboard.Key = Enum["KeyA", "KeyB", …]

An Enum covering the 88 Strings below. Each represents an individual button on a keyboard, independent of the character they might produce.

Each Keyboard.Key corresponds to one value of the W3C's UI Events KeyboardEvent.code.

W3C
Backquote
Digit1
Digit2
Digit3
Digit4
Digit5
Digit6
Digit7
Digit8
Digit9
Digit0
Minus
Equal
KeyQ
KeyW
KeyE
KeyR
KeyT
KeyY
KeyU
KeyI
KeyO
KeyP
BracketLeft
BracketRight
Backslash
KeyA
KeyS
KeyD
KeyF
KeyG
KeyH
KeyJ
KeyK
KeyL
Semicolon
Quote
KeyZ
KeyX
KeyC
KeyV
KeyB
KeyN
KeyM
Comma
Period
Slash
Space
Enter
Tab
Backspace
Escape
ShiftLeft
ShiftRight
ArrowLeft
ArrowRight
ArrowUp
ArrowDown
ControlLeft
ControlRight
AltLeft
AltRight
MetaLeft
MetaRight
CapsLock
Delete
Home
End
PageUp
PageDown
Numpad0
Numpad1
Numpad2
Numpad3
Numpad4
Numpad5
Numpad6
Numpad7
Numpad8
Numpad9
NumpadDecimal
NumpadAdd
NumpadSubtract
NumpadMultiply
NumpadDivide
NumpadEqual
NumpadEnter
IntlBackslash
typeKeyboard.TranslatedInput = Enum[typed: String, named: Keyboard.NamedKey]

One value of the W3C's UI Events KeyboardEvent.key:

  • typed: the key's String by the layout, such as "a", "A", "é", or " ".
  • named: a key with no String, by its name.

Python: Keyboard.Typed(string) and Keyboard.Named(key).

typeKeyboard.NamedKey = Enum["Enter", "Tab", …]

An Enum covering the Strings below: the W3C's named key attribute values for a keyboard's own keys. A named key outside them is "Unidentified".

GroupW3C
SpecialUnidentified
ModifierAlt AltGraph CapsLock Control Fn FnLock Meta NumLock ScrollLock Shift Symbol SymbolLock Hyper Super
WhitespaceEnter Tab
NavigationArrowDown ArrowLeft ArrowRight ArrowUp End Home PageDown PageUp
EditingBackspace Clear Copy CrSel Cut Delete EraseEof ExSel Insert Paste Redo Undo
UIAccept Again Attn Cancel ContextMenu Escape Execute Find Help Pause Play Props Select ZoomIn ZoomOut
DeviceBrightnessDown BrightnessUp Eject LogOff Power PowerOff PrintScreen Hibernate Standby WakeUp
CompositionAllCandidates Alphanumeric CodeInput Compose Convert Dead FinalMode GroupFirst GroupLast GroupNext GroupPrevious ModeChange NextCandidate NonConvert PreviousCandidate Process SingleCandidate HangulMode HanjaMode JunjaMode Eisu Hankaku Hiragana HiraganaKatakana KanaMode KanjiMode Katakana Romaji Zenkaku ZenkakuHankaku
FunctionF1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 Soft1 Soft2 Soft3 Soft4

Stimulus

Spatial

typePixel <: Float

A Pixel is the logical scene unit in nkl.

A scene unit is one W3C reference pixel. It is defined as the physical length of a pixel that, when viewed at a normal incidence angle by the agent, spans a visual angle equal to that spanned by a pixel with side length 1/96" when viewed from 28" away. The pixel centered at location (0, 0) with unit size spans roughly 0.0213°.

aliasLocation = Record[x: Pixel, y: Pixel]

(0, 0) is the center of the display; positive x is right; positive y is up.

aliasSpatial[A] <: Location -> A

A may be a Boolean, Float, Integer, or a Color.

functionSpatial.map(s: Spatial[A], f: A -> B) -> Spatial[B]

Functor. Pointwise application

functionSpatial.merge(items: Tuple[..., Spatial[A_n]], f: Tuple[...A_n] -> B) -> Spatial[B]

Variadic applicative.

Especially useful for applying Color.stack on a bunch of Spatial[Color] to composite them

Or for applying masking

functionSpatial.warp(spatial: Spatial[A], f: Location -> Location) -> Spatial[A]

Spatial.warp(s, f)(p) := s(f(p))

functionSpatial.translate(spatial: Spatial[A], dx: Pixel, dy: Pixel) -> Spatial[A]

Sugar, as the meaning can be captured by a .warp

Moves by positive (dx, dy)

functionSpatial.rotate(spatial: Spatial[A], degrees: Float) -> Spatial[A]

Sugar, as the meaning can be captured by a .warp.

Positive angles rotate the field counterclockwise about the origin.

functionSpatial.scale(spatial: Spatial[A], factor: Nonzero[Float]) -> Spatial[A]

Sugar, as the meaning can be captured by a .warp.

The picture becomes larger when factor>1. Scaling is about the origin

Color

typeColor

An abstract type. A Color describes a translucent light: the light it emits, and an opacity a from 0 to 1. The emitted light is three coordinates X, Y, Z in relative CIE XYZ (CIE 1931 2° standard observer). Y is luminance as a fraction of the reference white's. The reference white's luminance is the host's standard white: the luminance at which its platform shows ordinary white. Y = 0.5 requests half of it, and Y = 2 twice it, a light brighter than the reference white. The reference white is D65, the CIE standard daylight illuminant that sRGB and most displays take as white. It is defined by its CIE 1931 chromaticity, x = 0.3127, y = 0.3290, here at Y = 1; since X = x · Y / y and Z = (1 − x − y) · Y / y, that gives X ≈ 0.95046 and Z ≈ 1.08906. The luminance of the reference white on the host's display, in cd/m², is not known to the program. A Color's meaning is free of physical scale: ratios of light and chromaticity are exact, and the host's standard white sets the absolute luminance.

A Color in front of a light behind shows (X, Y, Z) + (1 − a) · behind: it adds its own light and lets the fraction 1 − a of behind through. A Color with a = 0 hides nothing; one with a = 0 and X = Y = Z = 0 is Transparent.

valueColor.Transparent: Color

The Color with a = 0 and X = Y = Z = 0 .

functionColor.srgba(r: Between[Float, 0, 1], g: Between[Float, 0, 1], b: Between[Float, 0, 1], a: Between[Float, 0, 1], additive: Boolean) -> Color

The Color with opacity a whose light has nonlinear sRGB coordinates r, g, b, using sRGB's transfer function and primaries but not its reference display luminance; r = g = b = 1 means the reference white as it appears on the host's display.

  • additive = False (straight sRGBA, as image files store it): the Color emits a times that light. With a = 0 it is transparent.
  • additive = True: the Color emits that light whatever a is. With a = 0 it adds its light and hides nothing, as a glowing gas does.
functionColor.stack(colors: List[Color]) -> Color

The colors stacked in order, the first at the bottom. Stacking top on bottom gives the (X, Y, Z, a) (X_top + (1 − a_top) · X_bottom, Y_top + (1 − a_top) · Y_bottom, Z_top + (1 − a_top) · Z_bottom, a_top + (1 − a_top) · a_bottom); more colors fold this from the left, and the empty List is Color.Transparent. Python: Color.stack(bottom, …, top) is it of [bottom, …, top].

functionColor.blend(color1: Color, color2: Color, t: Between[Float, 0, 1]) -> Color

The convex combination (1 − t) · color1 + t · color2, in each of X, Y, Z, and a: color1 at t = 0, color2 at t = 1. A fade out is Color.blend(c, Color.Transparent, t).

Curves

Open curves

typeCurve <: Float -> Location

In nkl, a Curve is a function of its parameter u to a Location. Its n pieces, excepting close's line back to start , take equal shares of u: piece k covers k/n ≤ u < (k+1)/n, with u running linearly in its Bézier parameter, and around an ellipse uniformly in angle. An open Curve is at its start for u ≤ 0 and at its end for u ≥ 1; a closed Curve repeats with period 1.

typeOpenCurve <: Curve
typeClosedCurve <: Curve
functionCurve.start(at: Location) -> OpenCurve

Just the point at for all time

functionCurve.line(from: OpenCurve, to: Location) -> OpenCurve
functionCurve.quad(from: OpenCurve, to: Location, c0: Location) -> OpenCurve
functionCurve.cubic(from: OpenCurve, to: Location, c0: Location, c1: Location) -> OpenCurve

Idiomatic python spelling:

python
triangle = (
    Curve.start([0, 0])
    .line(to=[1, 0])
    .line(to=[0, 1])
    .close()
)

Closed curves

functionCurve.close(curve: Curve) -> ClosedCurve

Closes the curve with a straight-line segment from its end back to its start, which takes no share of u. A closed Curve whose end is already at its start loops smoothly; otherwise it jumps back to its start each time u passes a whole number.

Shapes

typeEllipse <: ClosedCurve
functionshapes.Ellipse.create(center: Location, rx: Nonnegative[Pixel], ry: Nonnegative[Pixel]) -> Ellipse

Follows the right-hand rule; starts on the RHS vertex of the ellipse. Trajectory moves counterclockwise.

functionshapes.Ellipse.center(ellipse: Ellipse)->Location
functionshapes.Ellipse.rx(ellipse: Ellipse)->Nonnegative[Pixel]
functionshapes.Ellipse.ry(ellipse: Ellipse)->Nonnegative[Pixel]
typeRectangle <: ClosedCurve
functionshapes.Rectangle.create(center: Location, w: Nonnegative[Pixel], h: Nonnegative[Pixel]) -> Rectangle

Sugar, as the meaning can be represented by lines and a closed. Follows the right-hand rule; trajectory moves counterclockwise.

functionshapes.Rectangle.center(rectangle: Rectangle)->Location
functionshapes.Rectangle.width(rectangle: Rectangle)->Nonnegative[Pixel]
functionshapes.Rectangle.height(rectangle: Rectangle)->Nonnegative[Pixel]
functionshapes.Rectangle.top(rectangle: Rectangle)->Pixel
functionshapes.Rectangle.bottom(rectangle: Rectangle)->Pixel
functionshapes.Rectangle.left(rectangle: Rectangle)->Pixel
functionshapes.Rectangle.right(rectangle: Rectangle)->Pixel

Regions

functionCurve.border(curve: Curve, r: Float) -> Spatial[Boolean]

Returns the 'border' of a curve, which nkl defines as the neighborhoods of open balls of radius r. Note one can use this to make rectangles with rounded corners

functionCurve.interior(curve: ClosedCurve) -> Spatial[Boolean]

Returns the interior region of a ClosedCurve, where the points with nonzero winding number evaluate to True. Useful for hitboxes as well as painting. A point's winding number counts the curve's crossings of the ray from it toward +x, strictly to its right: +1 where the curve passes from y ≤ the point's y to above it, −1 where it passes back. So of two regions sharing an edge, each point on the edge lies in exactly one.

Text

Fonts

typeFont ≅ Record[name: String, sha256: String]

A font file: OpenType or TrueType, or a collection of them, whose faces are its members in order. sha256 is the SHA-256 of the file's bytes, 64 lowercase hexadecimal digits; name is what the font is called, and never changes how text lays out or draws. The host supplies its bytes, as it does a Media's.

aliasFont.Weight = Positive[Integer]

Each family draws the nearest weight it has. Python: "light", "normal", and "bold" are 300, 400, and 700.

Drawing text

typeText
functionText.create(string: String, font: Font, weight: Font.Weight) -> Text
functionText.join(first: Text, second: Text) -> Text
functionText.string(text: Text) -> String
typeTextLayout

An abstract type; it means a Spatial[Boolean]: the points a grapheme's ink covers, where its layout places it. Its value at a point never reaches a program's logic; it only decides what the display shows.

functionText.layout(text: Text, start: Location, width: Positive[Pixel], font_size: Positive[Pixel], line_height: Positive[Float]) -> TextLayout

Lays out the text in lines no wider than width, flowing in the positive x direction. line_height is the distance between baselines, as a multiple of font_size. Line k's baseline is at y = start.y − k · line_height · font_size, and each line starts at x = start.x.

functionTextLayout.outlines(layout: TextLayout) -> List[Spatial[Boolean]]

Each Character's ink, in order: one per Character of the String.

functionTextLayout.nearest_character(layout: TextLayout, location: Location) -> Nonnegative[Integer]

The index of the Character whose box is nearest location, ties to the first; 0 for empty text.

functionTextLayout.bounding_box(layout: TextLayout) -> Rectangle

The box around the layout's line boxes, not its ink.

functionTextLayout.selection_boxes(layout: TextLayout, start: Integer, end: Integer) -> List[Rectangle]

One box per line over the Characters between start and end, and the caret at end: after the Character before end when start < end, else before the Character at end. Indices are clamped between 0 and the length of the String. A line break's box is empty, at the end of its line.

External images and videos

typeMedia ≅ Record[sha256: String]

A value of abstract type Media represents the bytes of an audiovisual asset, where the host knows how to resolve the appropriate decoder given this Media value. Only visual decoding (.image) is currently supported.

sha256 is the SHA-256 of the file's bytes, as given, 64 lowercase hexadecimal digits.

Media.image represents the pixels decoded from the media: PNG, JPEG, WebP, and GIF as given (an animated GIF or WebP chosen by time), and video from MP4, MOV, and WebM files holding H.264, VP8, or VP9.

functionMedia.width(media: Media) -> Nonnegative[Pixel]
functionMedia.height(media: Media) -> Nonnegative[Pixel]

The picture's source size in texels as placed: after the file's orientation (EXIF, or a video track's display matrix).

functionMedia.duration(media: Media) -> Time

The length of the media, in microseconds: for an animated image, the sum of its frames' delays as stored; for a video, the end of its last picture on its timeline after the edit list, rounded up to a whole microsecond; for a still image, 0.

functionMedia.image(media: Media, at: Integer) -> Image

The picture whose time span holds at. Clamps between 0 and the media's duration. If there is no associated visual data (e.g., it is an audio file) is given, gives the transparent Color everywhere.

A w × h image is placed one texel per scene unit with its lower-left corner at (−⌊w/2⌋, −⌊h/2⌋): centred when a dimension is even, half a unit toward +x or +y when it is odd. Each texel covers the half-open square [i, i+1) × [j, j+1). Outside the image, it is the Transparent Color (0, 0, 0, 0).

typeImage <: Spatial[Color]

An abstract type; it means a Spatial[Color]. Its pixels cannot be directly evaluated by the program.

functionImage.place(image: Image, frame: Rectangle, fit: Literal["contain", "cover", "stretch"]='contain') -> Image

Resizes the image to fit inside of the given frame. This adjusts

contain: Preserve aspect ratio and show the whole image. cover: preserve aspect ratio and fill the frame; crop overflow stretch: scale each axis independently to match the frame

functionImage.bounding_box(image: Image) -> Rectangle

The size of the resized image pixel's, as placed

The result is transparent outside frame, and a frame with zero width or height gives a fully transparent result.

Randomness

aliasSeed = Integer
functionrandom.rng() -> Op[Seed]

random.rng()'s fresh randomness is one draw per run: the host draws a seed uniformly from 0 through 2⁵³ − 1 when the run starts and logs it, and the k-th random.rng() in run order, counting from 0, is random.integer(seed, k). A replay, or a simulation given other inputs, reads the seed and gets the same draws in the same order.

one Threefry-2×32-20 block, its key the seed's 64-bit two's complement and its counter the position's, low word first; for the block's output words x0 and x1, the result is (x0 · 2³² + x1) >> 11.

functionrandom.integer(seed: Seed, position: Integer) -> Nonnegative[Integer]

Pure, keyed randomness (Threefry-2×32-20, the top 53 bits)

String

typeString

A String is an ordered sequence of Character values. In nkl, a Character is a single Extended Grapheme Cluster as defined in Unicode 18.0, and the length of a String is the number of Character values it comprises. nkl's String type can be distinguished from the string type in other computer languages, in that nkl does not treat a single Unicode code point as a length-1 string. nkl's approach is inspired by the design of Swift's Character type.

typeCharacter <: String

A Character is a single Extended Grapheme Cluster as defined in Unicode 18.0, formed by one or more Unicode code points. A Character is a length-1 String.

expression"{string}" -> String

A String value may be constructed by writing a literal expression like "my new string", composed of a sequence of valid utf-8 codes.

expressionf"...{value}..."

meaning is String.join("", parts) with each number field given by String.from_number

functionString.from_number(x: Float) -> String

An integral Float is written in integer notation, so String.from_number(1.0) is "1" (1 and 1.0 are one value). Any other finite Float is written as the shortest decimal that reads back as the same Float, in Python's repr form: String.from_number(0.1) is "0.1".

functionString.join(separator: String, parts: List[String]) -> String

The parts with separator between each two; String.join("", parts) is their concatenation. Python: separator.join(parts). A result longer than 2⁵³ − 1 is IntegerOverflow.

functionString.words(string: String) -> List[Record[start: Nonnegative[Integer], end: Nonnegative[Integer]]]

The half-open Character spans, in order, of the string's default UAX #29 word segments (Unicode 18.0, no tailoring) that contain a code point of General_Category Letter or Decimal_Number. Empty text gives [].

functionString.slice(string: String, start: Option[Integer], stop: Option[Integer], step: Option[Integer]) -> String

As a List's, by graphemes. Python: s[a:b:c].

functionString.contains(string: String, part: String) -> Boolean

Whether part occurs in string as a run of whole Characters; the empty String occurs in every String. "é" does not contain "e". Python: part in s.

functionString.index(string: String, position: Integer) -> Character

The Character at position. Positions are as a List's. Python: s[i].

functionString.length(string: String) -> Nonnegative[Integer]

Its number of Character, at most 2⁵³ − 1. Python: len(s).

Logic

Booleans

typeBoolean
functionBoolean.not(x: Boolean) -> Boolean
functionBoolean.and(a: Boolean, b: Boolean) -> Boolean
functionBoolean.or(a: Boolean, b: Boolean) -> Boolean
functionBoolean.all(values: List[Boolean]) -> Boolean
functionBoolean.any(values: List[Boolean]) -> Boolean

Boolean.and and Boolean.or folded from the left; the empty List is True for Boolean.all and False for Boolean.any. Python: all(xs) and any(xs); any(test for x in xs) is it of [test for x in xs].

functionBoolean.to_integer(x: Boolean) -> Integer

False is 0 and True is 1. Python: int(x).

functionBoolean.to_float(x: Boolean) -> Float

False is 0.0 and True is 1.0. Python: float(x).

Comparison

operator(a: A) == (b: A) -> Boolean

Whether a and b are the same value. Numbers are equal when their values are, and Strings when they have the same code points. Lists are equal when they have the same length and their items are equal in order; Sets are equal as their entry says. Records are equal when every field is equal, and Enum values when they have the same case and equal payloads. A must not contain a function, SF, Signal, or Op. On every other A, == is identity.

For Time, in all of these operations, the same rules are followed, except that the units are taken into account correctly.

operator(a: A) < (b: A) -> Boolean

Whether a comes before b. A must be ordered: a Boolean, Integer, Float, String, or a List or Tuple of an ordered type. Strings, Lists, and Tuples come in lexicographic order, item by item, with Strings compared by code point; a proper prefix comes first. On an ordered type, exactly one of a < b, a == b, and b < a holds.

Not equal, less or equal, greater, and greater or equal are defined from these two.

operator(a: A) != (b: A) -> Boolean

This means Boolean.not(a == b). A is as for ==.

operator(a: A) <= (b: A) -> Boolean

This means Boolean.not(b < a). A must be ordered, as for <.

operator(a: A) > (b: A) -> Boolean

This means b < a. A must be ordered, as for <.

operator(a: A) >= (b: A) -> Boolean

This means Boolean.not(a < b). A must be ordered, as for <.

Numbers

Integers

typeInteger <: Float

Any integer from −9,007,199,254,740,991 through 9,007,199,254,740,991. Integers in nkl can always be used as Floats.

functionInteger.add(a: Integer, b: Integer) -> Integer
functionInteger.subtract(a: Integer, b: Integer) -> Integer
functionInteger.multiply(a: Integer, b: Integer) -> Integer
functionInteger.divide(a: Integer, b: Nonzero[Integer]) -> Float
functionInteger.negate(a: Integer) -> Integer
functionInteger.abs(a: Integer) -> Nonnegative[Integer]

A result past 2⁵³ − 1 is IntegerOverflow. Integer.divide is the exact quotient rounded once to the nearest Float. Python: a + b, a - b, a * b, a / b, -a, and abs(a).

Floats

typeFloat

A finite IEEE 754 binary64 value: NaN and the infinities are not members, of Float or of any type derived from it. There is one zero, +0.0: a literal, an imported value, and an arithmetic result that would be −0.0 are +0.0.

functionFloat.add(a: Float, b: Float) -> Float
functionFloat.subtract(a: Float, b: Float) -> Float
functionFloat.multiply(a: Float, b: Float) -> Float
functionFloat.divide(a: Float, b: Nonzero[Float]) -> Float
functionFloat.negate(a: Float) -> Float
functionFloat.abs(a: Float) -> Nonnegative[Float]

The exact result rounded once to the nearest Float; a result past the largest Float is NonFiniteResult. Python: a + b, a - b, a * b, a / b, -a, and abs(a).

functionFloat.to_integer(x: Float) -> Integer

Rounds toward zero.

Constraints

typePositive[A: (Integer, Float)]
typeNegative[A: (Integer, Float)]
typeNonnegative[A: (Integer, Float)]
typeNonzero[A:(Integer, Float)]
typeBetween[A: (Integer, Float), minimum: A, maximum: A]

Python: Annotated[A, Between(minimum, maximum)].

Basic math

Simple operations

functionmath.modulus(a: Nonnegative[Integer], b: Nonnegative[Integer]) -> Nonnegative[Integer]

The remainder of a divided by b, from 0 up to but not including b. A b of 0 is DivisionByZero.

functionmath.round(x: Float, places: Integer) -> Float

The nearest multiple of 10⁻ⁿ, n possibly negative. A tie goes to the even neighbor, on the exact binary value: 2.675 to 2 places gives 2.67, since 2.675 is stored as slightly less. Python: round(x) is math.floor(math.round(x, 0)).

functionmath.ceil(x: Float) -> Integer
functionmath.floor(x: Float) -> Integer
functionmath.min[A: (Integer, Float)](values: List[A]) -> A
functionmath.max[A: (Integer, Float)](values: List[A]) -> A

A List of one value or more, folded from the left; the empty List is InvalidArgument, having no identity among finite numbers. With no NaN and one zero, equal values are the same bits, so which of equals math.min and math.max return can't be observed. Python: min(xs) and max(xs); min(x, y, …) is it of [x, y, …].

functionmath.sum[A: (Integer, Float)](values: List[A]) -> A

Integer.add or Float.add folded from the left; the empty List is 0. Python: sum(xs); sum(term for x in xs) is it of [term for x in xs].

functionmath.power[A: (Integer, Float)](base: A, exponent: A) -> A

A negative base to a non-integral power is InvalidPower. An Integer to a negative Integer power is InvalidPower (DivisionByZero for base 0), and a result past 2⁵³ − 1 is IntegerOverflow. Python: a ** b.

functionmath.exp(x: Float) -> Float
functionmath.log(x: Positive[Float]) -> Float

The natural logarithm. Python: nkl.math.log(x, b) is math.log(x) / math.log(b).

Trigonometry

functionmath.cos(x: Float) -> Float
functionmath.sin(x: Float) -> Float
functionmath.tan(x: Float) -> Float
functionmath.atan2(y: Float, x: Float) -> Float

The angle of the point (x, y) from atan2(y, x), in [−π, π]; atan2(0, 0) is 0.

functionmath.hypot(values: List[Float]) -> Float

The distance from the origin, without overflow in between. More values fold the two-value case from the left; the empty List is 0.0. Python: nkl.math.hypot(x, y, …) is it of [x, y, …].

functionmath.sqrt(x: Nonnegative[Float]) -> Nonnegative[Float]

Containers

List

typeList[A]
functionList.create() -> List[A]

The empty List, its element type A from the expected type. Python: [] or list().

functionList.range(start: Integer, stop: Integer, step: Integer) -> List[Integer]

The Integers from start up to but not including stop, step apart; none when stop is not ahead of start in step's direction. A zero step is InvalidArgument, and a count past 2⁵³ − 1 is IntegerOverflow. Python: range(stop) writes start as 0 and step as 1, and range(start, stop) writes step as 1.

functionList.append(items: List[A], item: A) -> List[A]

Python: xs.append(x), as a statement.

functionList.map(items: List[A], f: A -> B) -> List[B]
functionList.reduce(items: List[A], f: (A, S) -> S, initial: S) -> S
functionList.filter(items: List[A], f: A -> Boolean) -> List[A]
functionList.concat(lists: List[List[A]]) -> List[A]

The Lists joined in order. A result longer than 2⁵³ − 1 is IntegerOverflow. Python: a comprehension's second for, and xs + ys is List.concat([xs, ys]).

functionList.zip(lists: Tuple[List[A₀], …, List[Aₙ]]) -> List[Tuple[A₀, …, Aₙ]]

The items together, position by position, as long as the shortest. Python: zip(xs, ys).

functionList.replace_index(list: List[A], position: Integer, item: A) -> List[A]

The List with item at position, counted as in List.index. Python: xs[i] = v.

functionList.slice(list: List[A], start: Option[Integer], stop: Option[Integer], step: Option[Integer]) -> List[A]

The items from start up to stop, every stepth, an absent bound being Python's omitted one. Bounds clip, a negative bound counts from the end, a negative step reverses, and a zero step is InvalidArgument. Python: xs[a:b:c].

expression{list}[{start}:{stop}:{step}]

The meaning is List.slice(list, start, stop, step), an omitted bound being absent; {list}[{start}:{stop}] omits step. On a String, it is String.slice.

expression[{item} for {name} in {items} if {test}]

The meaning is List.map(List.filter(items, lambda name: test), lambda name: item). Without if there is no List.filter, and several ifs are joined by and. With a further for, item is the comprehension of the clauses after this one, and the Lists it makes are joined by List.concat.

functionList.contains(list: List[A], item: A) -> Boolean

Python: x in xs.

functionList.index(items: List[A], position: Integer) -> A

Python: xs[i]; xs.index(v) is refused.

functionList.length(items: List[A]) -> Nonnegative[Integer]

Python: len(xs).

Set

typeSet[A]

A finite set of values of A, its members, no two equal; A must have ==. A Set has no order. Two Sets are equal when every member of each equals a member of the other. Of equal values, a Set holds the one it met first. The empty Set takes its element type from the expected type; Python: set().

functionSet.create(items: List[A]) -> Set[A]

The values of items, keeping the first of equal ones. Python: set(xs).

functionSet.add(set: Set[A], item: A) -> Set[A]

set with item as a member, or set itself when a member equals item. Python: s.add(x), as a statement.

functionSet.remove(set: Set[A], item: A) -> Set[A]

set without the member that equals item, or set itself when none does. Python: s.remove(x), as a statement.

functionSet.contains(set: Set[A], item: A) -> Boolean

Whether a member equals item. Python: x in s.

functionSet.length(set: Set[A]) -> Nonnegative[Integer]

Its number of members. Python: len(s).

functionSet.union(a: Set[A], b: Set[A]) -> Set[A]

The members of a, and those of b equal to no member of a. Python: a.union(b).

functionSet.intersection(a: Set[A], b: Set[A]) -> Set[A]

The members of a equal to a member of b. Python: a.intersection(b).

functionSet.difference(a: Set[A], b: Set[A]) -> Set[A]

The members of a equal to no member of b. Python: a.difference(b).

functionSet.symmetric_difference(a: Set[A], b: Set[A]) -> Set[A]

The members of each equal to no member of the other. Python: a.symmetric_difference(b).

functionSet.is_subset(a: Set[A], b: Set[A]) -> Boolean

Whether every member of a equals a member of b. Python: a.issubset(b).

functionSet.sorted(set: Set[A]) -> List[A]

The members, each < the next; A must be ordered. Python: sorted(s). It is the only entry through which a Set's members come in an order.

Product types

typeRecord[field₁: A₁, …, fieldₙ: Aₙ]

A structural record type: a product whose elements are named by distinct fields. A Record type is its set of fields, so the order they are written in is not part of it, and two Record types with the same fields of the same types are one type. A value has exactly the fields of its type. Two values are equal when every field is. In Python, a structural Record is built with nkl.Record(field₁=…, …) and has no annotation of its own.

A dictionary whose keys are all literal Strings is a spelling of a structural Record: {"foo": 3, "bar": 4} is a Record[foo: Integer, bar: Integer]. d["foo"] reads the field foo, and d["foo"] = v replaces it. A key known only at run time, adding or deleting a key, and iterating are refused.

typeR ≅ Record[field₁: A₁, …, fieldₙ: Aₙ]

A nominal record type, built into the core or declared by the program. Each declaration makes a new type, distinct from every other, including the structural Record with the same fields. A value carries its declaration, so a pattern can test for it. Two values are equal when they have the same declaration and every field is equal. In Python, a nominal Record is declared only as class R(nkl.Record):, with an annotation for each field. Only a Record class is called to construct a value; a value of an abstract type is made by its entries, such as Text.create.

aliasTuple[A₀, …, Aₙ₋₁] = Record[0: A₀, …, n−1: Aₙ₋₁]

A structural product whose elements are indicated by position. A Tuple has its own spelling and serialization, but its meaning is that of the structural Record whose fields are the positions 0 to n − 1: the same values, typing, and equality.

Sum types

typeEnum[case₁: A₁, …, caseₙ: Aₙ]

A labeled sum. The cases are case₁ to caseₙ, with distinct labels. Two Enum types are one when they have the same cases, with the same payload types. Two values are equal when they have the same case and equal payloads, so cases with the same payload type stay distinct. A case pattern in match narrows a value to that case's payload. Enum[case₁, …, caseₙ] is shorthand for an Enum whose payloads are all Nothing. A value is accepted where an Enum with the same cases and payload types is expected.

Python: Literal["a", "b"] is Enum[a, b], and a String literal is the case of that label.

aliasUnion[A₀, …, Aₙ₋₁] = Enum[0: A₀, …, n−1: Aₙ₋₁]

Union[A₀, …, Aₙ₋₁] is the Enum whose cases are the positions 0 to n − 1. No value is accepted by two of its members. Python: A | B; a value accepted by one member is the case at that member's position, and a match pattern on a member's type is a case pattern.

aliasOption[A] = Enum[some: A, none: Nothing]

An A, or none. Python: A | None; None is the case none, and a value of A is the case some.

Misc

typeA -> B

A function from an A to a B. -> groups to the right: A -> B -> C is A -> (B -> C).

(A₁, …, Aₙ) -> B is another spelling of A₁ -> … -> Aₙ -> B, and () -> B of Nothing -> B.

Python: a def or lambda with n parameters is an (A₁, …, Aₙ) -> B, and is called with its n arguments, f(a₁, …, aₙ).

Parameter names belong to the entry or def that declares them: a call may name its arguments where the callee’s declaration is known, and the names stand for positions.

A function is accepted where C -> D is expected when C is accepted where its A is, and its B is accepted where D is.

typeNothing

The unit type; its one value is None. In the Python spelling, None is the inhabitant of type Nothing.

functionhash(value: String) -> Integer

For a String, the 53 leftmost bits of the SHA-256 of its UTF-8, read as a big-endian unsigned integer. Python: nkl.hash(s); Python's builtin hash is refused.

expression{item} in {collection}

The meaning is List.contains(collection, item) on a List, Set.contains(collection, item) on a Set, and String.contains(collection, item) on a String. {item} not in {collection} is Boolean.not of it.

Python syntax

nkl is written in a subset of Python.

A module may hold any Python. nkl reads each function decorated with @nkl.function, each Record class declared from nkl.Record, each type alias, and the imports they use.

Computation

Declarations

statement{name} = {expression}

The meaning is let name = expression in rest, which is (lambda name: rest)(expression).

Python spellings that are this statement:

  • x += e is x = x + e.
  • a, b = t binds each item of the Tuple t.
  • x: T = e is x = e, checked at T.
  • r.f = v is r = replace(r, f=v); xs[i] = v, d[k] = v, and xs.append(v) rebind xs or d to the updated value. Each is accepted only when the value has no other reference.
  • def f(parameters) -> A: block is f = lambda parameters: block, with a block for its body; the IR keeps the name. The parameters' types and A are required. A def may not contain await. An async def is a do block: its block's meaning is an Op[A], as await and return say. A function may not capture a name that is assigned again after it, and may not call itself, directly or through other functions.
expressionlambda {parameters}: {body}

A function of parameters whose result is body. The parameters' types come from the expected type. A function captures the values of the names it uses when it is defined.

Branching

statementif {test}: {block} else: {block}

The meaning is match test: case True: block; j(…) case False: block; j(…), where j is a function of the locals the arms assign and runs rest. elif is an if in the else arm. a and b, a or b, and x if c else y are match on a Boolean.

Pattern matching

statementmatch {value}: case {pattern}: {block} …

Python's match. The cases are tried in order, and the first whose pattern matches and whose guard is true runs its block; arms that fall through continue with rest, as if's do.

Looping

statementfor {name} in {items}: {block}

The loop's state is a ControlFlow[S, R] = Enum[continue: S, break: S, return: R], where S is a Record of the locals the body assigns and R is the function's result. s is that Record before the loop. The body runs once per item, as step:

  • in a def, step(state, name) = match state: case ControlFlow.continue(s): block case _: state, and the meaning is match List.reduce(step, ControlFlow.continue(s), items): case ControlFlow.continue(s) | ControlFlow.break(s): rest case ControlFlow.return(v): v;
  • in an async def, step(state, name) = bind(state, lambda t: match t: case ControlFlow.continue(s): block case _: pure(t)), and the meaning is bind(List.reduce(step, pure(ControlFlow.continue(s)), items), lambda t: match t: case ControlFlow.continue(s) | ControlFlow.break(s): rest case ControlFlow.return(v): pure(v)).

Reaching the end of block is ControlFlow.continue(s), with s the body's locals. Inside the body, return value is ControlFlow.return(value). A for whose body has an await is an Op, since items may be empty.

statementbreak

The meaning is ControlFlow.break(s): the rest of the body doesn't run, and the remaining items leave the state as it is.

statementcontinue

The meaning is ControlFlow.continue(s): the rest of the body doesn't run, and the loop goes on to the next item.

Theorem

statementassert {test} -- FUTURE

A theorem the program states: test holds at this point. The program compiles only with a proof, checked by Lean, from the facts at that point; the rest of the block may then rely on test, so it narrows as an if would. assert test, message makes message the explanation when no proof is found. An assertion has no meaning at run time.