Skip to content

Type conversion and reflection

Tim Hardcastle edited this page Feb 29, 2024 · 8 revisions

Type conversion

Charm has a number of built-in functions for type conversion.

Usually they have the same name as the type they convert to:

eval converts a string representing a Charm expression into the value it would evaluate to, e.g. eval "2 + 2" is 4.

float64 converts ints to float64s, or converts strings to float64s if they have the right format.

int converts float64s to integers by truncation, or converts strings to ints if they have the right format.

literal converts a value into a string which is the Charm literal of that value.

set will turn a tuple or list into a set.

string will convert anything to a string.

tuple will leave a tuple unchanged and turn anything else in to a tuple of arity 1.

tuplify will convert a list into a tuple with the same elements.

type converts a value to its type.

Note that to turn a tuple t into a list it is only necessary to wrap it in brackets: [t].

Reflection

In the list above we briefly noted that type converts a value to its type. That is, type "walrus" evaluates to string, type 42 evaluates to int, etc.

string and int are themselves members of the type type. That is, type string returns type.

type is a perfectly normal Charm type itself, and belongs, of course, to type type. Try not to let this bother you.

We can also use the in keyword to check for type membership: so for example "walrus" in string and string in type are true.

🧿 Pipefish

Clone this wiki locally