Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Conversions with to

There are three ways to change a domain, and each has one meaning:

SyntaxMeaningRuntime cost
implicitWidening, or a range the checker provednone
x as TAssertion: x is already in Tone check
x to TConversion: changes the valuesthe conversion itself

The to table

A to with a domain makes one of these conversions, chosen from x’s type:

FromToOperationMatches
u8Unit$x / 255$a u8 dtype, any domain
UnitSigned$2x - 1$a float range within $[0, 1]$
SignedUnit$(x + 1) / 2$a float range within $[-1, 1]$ but not within $[0, 1]$
MaskBinaryfloat castMask
MaskAdditive0 where true, $-\infty$ where falseMask
Logit over CProb over Csoftmax over Canything that fits Logit over C, including plain numbers
Logit over CLogProb over Clog-softmax over Cas above

Anything else is E0504, which lists the table. That includes semantic and discrete domains matched against range rows by their values (Prob to Signed; assert first, p as Unit |> to Signed), and converting to the domain a value already has (“nothing to convert”).

u8 to Unit and Mask to Binary or Additive give the default float dtype; the others keep the float dtype. A to may also write a dtype, as in to Unit f16, which must be a float (E0504). A to with a domain on a Python value is E0413, because the conversion depends on a type the value doesn’t have yet. The shape in to [b C] Unit, if given, must be x’s (E0401).

Converting dtypes

A to with only a dtype changes how values are stored and keeps them:

  • bool to a float gives Binary, and to an integer gives $[0, 1]$;
  • an integer to a float keeps the range; a float to an integer truncates it;
  • a float to a lower-precision float rounds the range’s ends outward;
  • anything but bool to bool is E0504: compare instead, as in x != 0.

A dtype-only to on a Python value is allowed and leaves it a Python value.