Skip to content

Implicit and Explicit Casting

C272 edited this page Aug 19, 2019 · 3 revisions

Implicit Casts

Algo is strongly typed, but uses implicit casts to make sensible operations work properly (for example, float + int will create a float, and won't throw an error). When casting, you can only go up the casting hierarchy without using explicit casts.

Here's the route that a value will take when you're casting, starting from an integer.

integer -> rational -> float -> string
integer -> boolean

An integer can be cast to any value (eg. rational, float, string, boolean), but only to a boolean when it's 0 or 1. Rationals can only be cast to a float or a string, and floats can only be cast to string. Strings cannot be cast to anything.

Explicit Casts

To cast explicitly from a sensible source, such as string to integer, you can use the following functions.

let x = ...
str(x) //converts to string
int(x) //converts to int
flt(x) //converts to float
rat(x) //converts to rational
bool(x) //converts to bool

Obviously some casts are impossible, such as boolean to rational, and these will simply throw errors if casts are attempted.