Types
Cresset checks types before your program runs, but you don't have to write them. It works out what it can from your code, and only complains when it is certain something is wrong.
It infers types
fn main() needs print:
n = 5
words = "a b c".split()
print(n + 1, words.len())
Cresset knows n is a number and words is a list of text, because of what was assigned. Mistakes get caught without any annotation:
fn main() needs print:
n = 5
print("n=" + n)
error: can't add text and a number
--> example.crs:3
help: to put a number inside text, write it in braces: "total: {n}"
Optional annotations
Add types where you want a promise held. Put a type after a parameter name, and -> before the colon for the return type:
fn describe(name: text, score: num) -> text:
return "{name} scored {score}"
fn main() needs print:
print(describe("Ada", 9))
Calling it with the wrong kind of value is caught before anything runs:
fn describe(name: text, score: num) -> text:
return "{name} scored {score}"
fn main() needs print:
print(describe("Bob", "five"))
error: 'describe' expects 'score' to be a number, but this is text
The types are num, text, bool, none, any, rng (a seeded random generator), list[T], map[T], result[T], and the names of your own records and enums. For example, list[num] is a list of numbers. Plain list, map and result mean "of anything".
What it catches
- Wrong number of arguments, or the wrong type of argument, to your functions and to built-ins
text + number, and other operations on the wrong kinds of values- Misspelled methods and fields, with a "did you mean" suggestion
- Using a name that doesn't exist
?on something that isn't a result- Returning the wrong type from a function that says what it returns
- Calling something that isn't a function, or indexing something that can't be indexed
- All of the above across package boundaries
It is gradual
Anything Cresset can't work out is treated as "could be anything", and anything never causes an error. That is why correct, dynamic code is never rejected:
fn pick(flag, a, b):
if flag: return a
return b
fn main() needs print:
x = 5
x = "now it is text"
print(pick(true, 1, "a"), x)
Limits
- Annotations are checked before the program runs, not while it runs. A function that is declared to take a number and gets a value that Cresset couldn't see the type of is not stopped at run time.
- Parameters you don't annotate count as "anything", so checking inside such a function is weaker.
- There are no generics, and no way yet to give a function type as an annotation.
Next
Make your own types: Records, enums and match.