Chapter 7 of 14

Functions and modules

A function gives a reusable piece of work a name. A module keeps related functions in another .crlo file.

Make a function

To welcome using name.
  Return "Hello, " followed by name.
End.

Run it with a value:

Run welcome with "Asha" into message.
Show message.

The function receives name, builds the result, and returns it into message.

Why functions help

Functions let you:

  • avoid copying the same instructions
  • give work a clear name
  • keep the main program short
  • test one piece at a time
  • change shared behavior in one place

Use clear inputs

To make greeting using name.
  Set text to "Welcome, " followed by name.
  Return text.
End.

Choose input names that explain what the function needs.

Keep one purpose

A function named make greeting should make a greeting. It should not also delete files or send an unrelated request.

Small functions are easier to read and check.

Connect another file

Create message.crlo:

To welcome using name.
  Return "Welcome, " followed by name.
End.

Use it from main.crlo:

Use "message.crlo".

Run welcome with "Asha" into message.
Show message.

A connected module loads once. Creole rejects circular module connections.

Organize a larger program

assistant/
  @.crlo
  main.crlo
  chat.crlo
  request.crlo
  memory.crlo
  tools.crlo

Possible responsibilities:

  • main.crlo starts the program
  • chat.crlo controls conversation flow
  • request.crlo handles provider requests
  • memory.crlo reads and saves memory
  • tools.crlo keeps reusable tools

These are file names, not required Creole words. Choose names that fit your project.

Avoid circular connections

Do not let chat.crlo use memory.crlo while memory.crlo eventually connects back to chat.crlo.

Move shared work into a third module that both files can use.

Practice

Create math-help.crlo:

To double using number.
  Return number times 2.
End.

Create main.crlo:

Use "math-help.crlo".
Run double with 8 into result.
Show result.

Learning checklist

  • I can define a function with To.
  • I can receive an input.
  • I can return a result.
  • I can run a function.
  • I can connect another .crlo file.
  • Each module has one clear responsibility.

Next step

Continue to Files and data to read, write, organize, and save information.