Skip to content

Introducing functions

tim-hardcastle edited this page Aug 27, 2023 · 12 revisions

In this page we will look at the basics of functions.

Here are some examples, in examples/func1.ch.

def

square (x) : x * x

parity (x) : 
    x % 0 == 0 : "even"
    else : "odd"

Some things to note:

The body of a Charm function consists of a single expression to be evaluated. There is no return keyword because all a Charm function ever does is return something, so it would be superfluous to have a keyword to point this out.

In Charm, a : precedes the body of a code block, which may be on the same line as the : so long as it fits into one line. Otherwise the block must also be marked off by indentation, as in the parity function.

Within the body of a function : also implicitly means "if the condition on the left, then the thing on the right", because there is no other reason why one would want a code block in a function.

Functions are defined in the def section of the script.

🧿 Pipefish

Clone this wiki locally