Language tour

A quick walk through the everyday parts of Cresset. Every complete example on this page is compiled when the docs are built, so they work.

Values and variables

There is no keyword for creating a variable. Assign to a name and it exists.

fn main() needs print:
    count = 3
    price = 4.5
    name = "Ada"
    ready = true
    nothing = none
    count += 1
    print("{name} bought {count} for {count * price}")
    print(ready, nothing)

The value types are numbers, text, true and false, none, lists, and maps. All numbers are floating point, so 7 / 2 is 3.5; use floor(7 / 2) for 3.

Text

Put any expression inside { } in a piece of text and its value is inserted. You can use quotes inside the braces. Write \{ for a literal brace. The escapes are \n, \t, \", \\, \{ and \}.

fn main() needs print:
    first = "Ada"
    last = "Lovelace"
    print("{first.upper()} {last.lower()} has {len(first)} letters")
    print("a" + "b", "ab" * 3)

Text in single quotes is taken exactly as written: no insertions, and \ and { mean themselves. That makes it the easy way to write anything brace-heavy, like JSON. It can't contain a single quote, and it stays on one line.

fn main() needs print:
    data = json_parse('{"name": "Ada", "scores": [90, 72]}')
    print(data.unwrap()["scores"])
    print('{not inserted} and \n is not a newline')

For text over several lines, use triple quotes. """...""" allows {insertions} and escapes like ordinary text, and '''...''' is taken exactly as written. The newline after the opening quotes and the one before the closing quotes are dropped, and the indentation every line shares is removed, so you can indent the text to match your code:

fn main() needs print:
    name = "Ada"
    letter = """
        Dear {name},

          Your tour of Cresset is ready.
        """
    print(letter)
    config = '''
        {"theme": "dark", "tabs": 4}
        '''
    print(json_parse(config).unwrap()["tabs"])

Adding text and a number is an error, because it is nearly always a mistake. Put the number in braces instead: "total: {n}".

Lists and maps

fn main() needs print:
    scores = [90, 72, 85]
    scores.push(60)
    print(scores[0], scores[-1], scores.len())
    ages = {ada: 36, "bob": 41}
    ages.set("cy", 29)
    print(ages["ada"], ages.get("zed", 0))
    for name, age in ages.items():
        print("{name} is {age}")

Negative list indexes count from the end. A map key written as a plain name is the text of that name, so {ada: 36} and {"ada": 36} are the same. Looping over a map directly gives its keys; use .items() for key and value pairs.

Decisions and loops

fn grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    else:
        return "C or below"

fn main() needs print:
    for score in [95, 82, 40]:
        print(grade(score))
    n = 0
    while n < 3:
        n += 1
        if n == 2: continue
        print("n is {n}")

Conditions can combine with and, or and not, and x in list tests membership. These count as false: false, none, 0, empty text, an empty list and an empty map. Everything else is true. == compares values by content, including lists, maps, records and enums.

Functions and lambdas

fn average(values):
    return values.sum() / values.len()

fn main() needs print:
    double = x -> x * 2
    add = (a, b) -> a + b
    print(double(21), add(1, 2))
    print([1, 2, 3].map(double))
    print(average([2, 4, 6]))

A function can read variables defined at the top of the file, but it can never change them: assigning inside a function always makes a new local variable. Trying to update an outside variable with += is an error, so a function's effect on the world is only what it returns.

count = 0

fn bump():
    count += 1

fn main() needs print:
    bump()
    print(count)
error: 'count' belongs to the outside of this function, so it can't be changed from here
help: give it a local name first (like  total = count), or return the new value instead

A short function body can sit on the same line: if n < 2: return n. Functions can call themselves; very deep recursion (over 800 calls) stops with an error instead of crashing.

Methods you will use most

There are also math helpers (sqrt, pow, ceil), fixed for formatting numbers, and json_parse / json_stringify. All of these are pure, so they need no permissions. The full list, with what each returns, is in the reference.

What comes next

Things that touch the outside world need permission: Effects and permissions. Things that can fail return a result: Errors and contracts.