Help me understand the Motoko documentation

I feel I need some help in reading and understanding the Motoko documentation to advance more rapidly and with less trial-and-error. I’ve got a background in Python which feels way easier to grasp tbh. Also it’s older so I can just google many things. Let’s take the find function for Arrays as an example. The documentation says the following:

func find<A>(xs : [A], f : A -> Bool) : ?A

These are my questions:

  1. What does <A> stand for? Are <> just placeholders for variables in the documentation?
  2. What do question marks stand for? I’ve seen them preceding variables ?A but also seemingly indicate optional notations like <sort> <id>? =? <obj-body>, i.e. in the language quick reference.
  3. What does xs stand for and why xs?

Here’s my take at using the find function on an Array:

var myArray : [Nat] = [2, 4, 6];
Array.find(myArray, func x {x == 2});

And this would be the corresponding notation in natural language:

Run a function on myArray that returns a Boolean value for each entry in that array.

This means that I’m expecting it to return an Array with Boolean values but this doesn’t seem to be the case. How can I tell from the documentation what a function returns?

Here’s another take:

var myArray : [Nat] = [2, 4, 6];
Array.find(myArray : [Nat], func x {x == 2});

But something tells me it might as well work like this:

var myArray : [Nat] = [2, 4, 6];
Array.find<Bool>(myArray, func x {x == 2});

Can anybody tell what my problem is?

1 Like

<A> is a generic type parameter to the find() function. Think about it like a type that you need to declare (i.e. Text, Nat, etc.) in order for the compiler to infer you’re passing the correct function parameters and are returning the expected type.

Whichever one of these types you supply to <A>, find() will expect the type signature of the function value you supply to the f parameter as well as the return value to match this <A> type.

Example:

let firstEven = Array.find<Nat>([1,2,3,4], func(x: Nat) { x % 2 == 0 })

I’ve found digging around the base library to be very helpful when it comes to learning more about Motoko and what a specific function does. For example, here is the implementation of Array.find

3 Likes

The test suite also usually has example usage.

3 Likes

What does xs stand for and why xs?

It’s a parameter name. It was chosen to indicate the plural form of “x” in English, where “x” represents an arbitrary array element.

1 Like