### Full lifecycle example: Initial deployment Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/2-actors/8-enhanced-multi-migration.md The first step in an actor's state evolution is the initial deployment, defining the starting state. ```motoko // migrations/20250101_000000_Init.mo module { public func migration(_ : {}) : { a : Nat } { { a = 0 } } } ``` ```motoko actor { var a : Nat; } ``` -------------------------------- ### Motoko Secondary Constructor Call with #install Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/16-language-manual.md Example of calling the secondary constructor with the '#install' variant to install an actor to a pre-existing, empty ICP principal. ```motoko (system Lib.)(#install p)(, ...​, ) ``` -------------------------------- ### Motoko: Installing Actor Class Instances with Settings Source: https://github.com/caffeinelabs/motoko/blob/master/Changelog.md Shows how to install actor class instances on the IC with specified canister settings. This uses a secondary constructor that takes an additional argument for installation control. ```motoko await (system Lib.Node)(#upgrade a)(i); ``` -------------------------------- ### Map Example: Explicit vs. Implicit Parameters Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/11-implicit-parameters.md Demonstrates adding and getting elements from a Map, showing the difference between explicitly providing the comparison function and relying on inferred implicit parameters. ```motoko import Map "mo:core/Map"; import Nat "mo:core/Nat"; let inventory = Map.empty(); // Old style: explicitly pass Nat.compare Map.add(inventory, Nat.compare, 101, "Widget"); Map.add(inventory, Nat.compare, 102, "Gadget"); Map.add(inventory, Nat.compare, 103, "Doohickey"); let item1 = Map.get(inventory, Nat.compare, 102); // With contextual dots and implicits: compare function inferred inventory.add(101, "Widget"); inventory.add(102, "Gadget"); inventory.add(103, "Doohickey"); let item2 = inventory.get(102); ``` -------------------------------- ### Get Current System Time and Calculate Elapsed Seconds Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Time.md This example demonstrates how to get the current system time using `Time.now()` and calculate the elapsed seconds since the last call. Ensure `moc` is not invoked with `-no-timer` to avoid import failures. Timer resolution is tied to the block rate, so choose durations carefully. ```motoko import Int = "mo:core/Int"; import Time = "mo:core/Time"; persistent actor { var lastTime = Time.now(); public func greet(name : Text) : async Text { let now = Time.now(); let elapsedSeconds = (now - lastTime) / 1000_000_000; lastTime := now; return "Hello, " # name # "!" # " I was last called " # Int.toText(elapsedSeconds) # " seconds ago"; }; }; ``` -------------------------------- ### Periodic Reminder Timer Example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/icp-features/2-timers.md This example demonstrates setting up a periodic reminder that logs a message. It utilizes the Timer.mo module for timer management. ```motoko actor { stable var count = 0; public func init() { // Set a timer to call 'tick' every 5 seconds Timer.set(5_000_000_000, func () { tick(); }); }; public func tick() { count := count + 1; // Log a new year's message every 10 ticks (50 seconds) if (count % 10 == 0) { print("Happy New Year!"); } else { print("Tick!"); }; }; } ``` -------------------------------- ### Motoko Secondary Constructor Call with #upgrade Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/16-language-manual.md Example of calling the secondary constructor with the '#upgrade' variant to install an actor as an upgrade of an existing actor, preserving its stable state. ```motoko (system Lib.)(#upgrade a)(, ...​, ) ``` -------------------------------- ### Motoko doc comment example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/motoko-tooling/3-mo-doc.md Demonstrates the use of Motoko doc comments (`///`) for documenting functions, including examples within the comments. ```motoko /// Calculate the factorial of a given positive integer. /// /// Example: /// ```motoko /// factorial(0); // => null /// factorial(3); // => ?6 /// ``` func factorial(n : Nat) : ?Nat { // ... } ``` -------------------------------- ### Queue Usage Example - Motoko Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Queue.md Demonstrates basic queue operations like adding elements to the back and removing them from the front. This example shows how to use the Queue for FIFO behavior. ```motoko import Queue "mo:core/Queue"; persistent actor { let orders = Queue.empty(); Queue.pushBack(orders, "Motoko"); Queue.pushBack(orders, "Mops"); Queue.pushBack(orders, "IC"); assert Queue.popFront(orders) == ?"Motoko"; assert Queue.popFront(orders) == ?"Mops"; assert Queue.popFront(orders) == ?"IC"; assert Queue.popFront(orders) == null; } ``` -------------------------------- ### Explicit Safe Migration Example Source: https://github.com/caffeinelabs/motoko/blob/master/Changelog.md This example demonstrates renaming a stable field and changing its type during an upgrade. Ensure to consult the documentation for full details. ```motoko import Nat32 "mo:base/Nat32"; (with migration = func (old : { var size : Nat32 }) : { var length : Nat } = { var length = Nat32.toNat(old.size) } ) persistent actor { var length : Nat = 0; } ``` -------------------------------- ### Example: paginated map view .view() method Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/icp-features/7-view-queries.md An example of a .view() method for a Map.Map type that provides paginated access to its entries. It accepts optional key and count arguments. ```motoko module MapView { public func view( self : Map.Map, compare : (implicit : (K, K) -> Order.Order) ) : (ko : ?K, count : ?Nat) -> [(K, V)] = func(ko, count) { let entries = switch ko { case null { self.entries() }; case (?k) { self.entriesFrom(k) }; }; switch count { case null { entries.toArray() }; case (?c) { entries.take(c).toArray() }; }; }; } ``` -------------------------------- ### Capture Installer Principal in Actor Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/icp-features/3-caller-identification.md When an actor needs access to its installer's principal, declare it as a zero-argument actor class and capture `msg.caller` in a `let` binding. ```motoko shared(msg) actor class InstallerAware() { let installer = msg.caller; // This is the principal of the installer public func whoInstalled() : async Principal { installer } } ``` -------------------------------- ### Motoko Switch Statement Example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/5-control-flow/5-switch.md Demonstrates a basic switch statement with pattern matching on a custom data type. This example shows how to destructure variants and handle different cases. ```motoko type Exp = {#Lit : Nat; #Div : (Exp, Exp); #If : (Exp, Exp, Exp)}; func eval(e : Exp) : ? Nat { do ? { switch e { case (#Lit n) { n }; case (#Div (e1, e2)) { let v1 = eval e1 !; let v2 = eval e2 !; if (v2 == 0) null ! else v1 / v2 }; case (#If (e1, e2, e3)) { if (eval e1 ! == 0) eval e2 ! else eval e3 ! }; }; }; }; let expr : Exp = #If( #Div(#Lit 10, #Lit 2), // 10 / 2 = 5 (non-zero, so evaluate e3) #Lit 0, // e2 (ignored because e1 ≠ 0) #Div(#Lit 6, #Lit 3) // e3 → 6 / 3 = 2 ); eval(expr); ``` -------------------------------- ### Motoko HashMap mapFilter Example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/base/HashMap.md Demonstrates the usage of HashMap.mapFilter to transform entries. In this example, entries with a value of 2 are filtered out, and other values are doubled. The expected result of getting 'key3' is shown. ```motoko map.put("key1", 1); map.put("key2", 2); map.put("key3", 3); let map2 = HashMap.mapFilter( map, Text.equal, Text.hash, func (k, v) = if (v == 2) { null } else { ?(v * 2)} ); map2.get("key3") // => ?6 ``` -------------------------------- ### Migration Function Example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/2-actors/8-enhanced-multi-migration.md An example migration function that transforms state fields. It reads 'a' and 'b', outputs 'a' as Int and a new field 'd'. 'b' is consumed, and 'c' (not shown) would pass through unchanged. ```motoko module { public func migration(old : { a : Nat; b : Text }) : { a : Int; d : Float } { { a = old.a; d = 1.0 } } } ``` -------------------------------- ### Get the Size of a Queue Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/pure/Queue.md Retrieve the number of elements currently in the queue. This example checks the size of a queue with one element. ```motoko persistent actor { let queue = Queue.singleton(42); assert Queue.size(queue) == 1; } ``` -------------------------------- ### Initialize and Use PriorityQueue Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/PriorityQueue.md Demonstrates initializing an empty priority queue, pushing elements with a comparison function, and popping them in priority order. Asserts the expected order of elements. ```motoko import PriorityQueue "mo:core/PriorityQueue"; import Nat "mo:core/Nat"; persistent actor { let pq = PriorityQueue.empty(); PriorityQueue.push(pq, Nat.compare, 5); PriorityQueue.push(pq, Nat.compare, 10); PriorityQueue.push(pq, Nat.compare, 3); assert PriorityQueue.pop(pq, Nat.compare) == ?10; assert PriorityQueue.pop(pq, Nat.compare) == ?5; assert PriorityQueue.pop(pq, Nat.compare) == ?3; assert PriorityQueue.pop(pq, Nat.compare) == null; } ``` -------------------------------- ### Generate Infinite Nat Iterator Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Nat.md Use `allValues` to get an infinite iterator that yields all possible `Nat` values starting from 0. ```motoko import Iter "mo:core/Iter"; let iter = Nat.allValues(); assert iter.next() == ?0; assert iter.next() == ?1; assert iter.next() == ?2; // ... ``` -------------------------------- ### Usage Example for Tuples Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Tuples.md Demonstrates basic usage of Tuple2 and Tuple3, including swapping elements and converting to text. ```motoko import { Tuple2; Tuple3 } "mo:core/Tuples"; import Bool "mo:core/Bool"; import Nat "mo:core/Nat"; let swapped = Tuple2.swap((1, "hello")); assert swapped == ("hello", 1); let text = Tuple3.toText((1, true, 3), Nat.toText, Bool.toText, Nat.toText); assert text == "(1, true, 3)"; ``` -------------------------------- ### Example: Generate Random Index (Motoko) Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Random.md Demonstrates how to generate a random Nat value for an index within a specified range using a seeded random number generator. This example uses a deprecated function. ```motoko let random = Random.seed(42); let index = random.natRange(0, 10); // 0 to 9 ``` -------------------------------- ### Extract a sub-Buffer Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/base/Buffer.md Use `subBuffer` to get a portion of a buffer. Specify the starting index and the desired length. Traps if indices are out of bounds. ```motoko import Nat "mo:base/Nat"; buffer.add(1); buffer.add(2); buffer.add(3); buffer.add(4); buffer.add(5); buffer.add(6); let sub = Buffer.subBuffer(buffer, 3, 2); Buffer.toText(sub, Nat.toText); // => [4, 5] ``` -------------------------------- ### Construction and Basic Operations Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/pure/RealTimeQueue.md Demonstrates how to create an empty queue, check if it's empty, create a singleton queue, and get its size. ```APIDOC ## Function `empty` ``` motoko no-repl func empty() : Queue ``` Create a new empty queue. Example: ```motoko include=import import Queue "mo:core/pure/RealTimeQueue"; persistent actor { let queue = Queue.empty(); assert Queue.isEmpty(queue); } ``` Runtime: `O(1)`. Space: `O(1)`. ## Function `isEmpty` ``` motoko no-repl func isEmpty(self : Queue) : Bool ``` Determine whether a queue is empty. Returns true if `queue` is empty, otherwise `false`. Example: ```motoko include=import import Queue "mo:core/pure/RealTimeQueue"; persistent actor { let queue = Queue.empty(); assert Queue.isEmpty(queue); } ``` Runtime: `O(1)`. Space: `O(1)`. ## Function `singleton` ``` motoko no-repl func singleton(element : T) : Queue ``` Create a new queue comprising a single element. Example: ```motoko include=import import Queue "mo:core/pure/RealTimeQueue"; persistent actor { let queue = Queue.singleton(25); assert Queue.size(queue) == 1; assert Queue.peekFront(queue) == ?25; } ``` Runtime: `O(1)`. Space: `O(1)`. ## Function `size` ``` motoko no-repl func size(self : Queue) : Nat ``` Determine the number of elements contained in a queue. Example: ```motoko include=import import Queue "mo:core/pure/RealTimeQueue"; persistent actor { let queue = Queue.singleton(42); assert Queue.size(queue) == 1; } ``` Runtime: `O(1)`. Space: `O(1)`. ``` -------------------------------- ### Iterate Over All Nat8 Values Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Nat8.md Use `allValues` to get an iterator that yields every possible Nat8 value, starting from 0 up to the maximum value. ```motoko import Iter "mo:core/Iter"; let iter = Nat8.allValues(); assert iter.next() == ?0; assert iter.next() == ?1; assert iter.next() == ?2; // ... ``` -------------------------------- ### Stack Class Initialization Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/base/Stack.md Demonstrates how to create a new Stack instance. ```APIDOC ## Class `Stack` ``` motoko no-repl class Stack() ``` Class `Stack` provides a minimal LIFO stack of elements of type `T`. See library `Deque` for mixed LIFO/FIFO behavior. Example: ```motoko name=initialize import Stack "mo:base/Stack"; let stack = Stack.Stack(); // create a stack ``` ``` -------------------------------- ### Test .wat File with C Source: https://github.com/caffeinelabs/motoko/blob/master/test/README.md Example of a `.wat` file used for testing `mo-ld`. These expect a corresponding `.c` file. ```wat foo.wat ``` -------------------------------- ### FoldRight Iterator Example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Iter.md Applies a combining function to iterator elements in reverse, starting with an initial accumulator. Note: This function materializes the entire iterator in memory. ```motoko let iter = ["A", "B", "C"].values(); let result = Iter.foldRight(iter, "S", func (x, acc) = "(" # x # acc # ")"); assert result == "(A(B(CS)))"; ``` -------------------------------- ### Get Map Size in Motoko Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Map.md Use this function to retrieve the number of entries in a map. It's an O(1) operation. Examples show checking size before and after clearing the map. ```motoko import Map "mo:core/Map"; import Nat "mo:core/Nat"; persistent actor { let map = Map.fromIter( [(0, "Zero"), (1, "One"), (2, "Two")].values(), Nat.compare); assert Map.size(map) == 3; Map.clear(map); assert Map.size(map) == 0; } ``` -------------------------------- ### Create and Use a Counter Class Instance Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/4-declarations/4-class-declarations.md Demonstrates defining a simple Counter class with an initial value and an increment method, then creating an instance and using its method. ```motoko class Counter(init : Nat) { var count : Nat = init; public func inc() : Nat { count += 1; count }; }; // Creating an instance of the class let myCounter = Counter(0); // Using the instance myCounter.inc(); // returns 1 ``` -------------------------------- ### Set Example: Explicit vs. Implicit Parameters Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/11-implicit-parameters.md Illustrates adding elements to a Set and checking for their existence, comparing the explicit method of providing `Text.compare` with the implicit, inferred approach. ```motoko import Set "mo:core/Set"; import Text "mo:core/Text"; let tags = Set.empty(); // Old style Set.add(tags, Text.compare, "urgent"); Set.add(tags, Text.compare, "reviewed"); let hasTag1 = Set.contains(tags, Text.compare, "urgent"); // With implicits tags.add("urgent"); tags.add("reviewed"); let hasTag2 = tags.contains("urgent"); ``` -------------------------------- ### Iterate Set Elements in Descending Order Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Set.md Use `reverseValuesFrom` to get an iterator for set elements starting from a specific element in descending order. Ensure the comparison function is provided. ```motoko import Set "mo:core/Set"; import Nat "mo:core/Nat"; import Iter "mo:core/Iter"; persistent actor { let set = Set.fromIter([0, 1, 3].values(), Nat.compare); assert Iter.toArray(Set.reverseValuesFrom(set, Nat.compare, 0)) == [0]; assert Iter.toArray(Set.reverseValuesFrom(set, Nat.compare, 2)) == [1, 0]; } ``` -------------------------------- ### Example: Using Contextual Dot Notation with Array Module Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/10-contextual-dot.md Demonstrates the equivalence of traditional functional style and contextual dot notation for array mapping. It uses an assertion to verify that both methods produce identical results. ```motoko import Array "mo:core/Array"; import Nat "mo:core/Nat"; let numbers = [1, 2, 3, 4]; // Traditional functional style let doubled1 = Array.map(numbers, func(n) { n * 2 }); // Using contextual dot notation let doubled2 = numbers.map(func(n) { n * 2 }); // Both produce the same result assert Array.equal(doubled1, doubled2, Nat.equal); ``` -------------------------------- ### Iterate Over All Nat16 Values Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Nat16.md Use this function to get an iterator that yields every possible Nat16 value, starting from 0 up to the maximum value for Nat16. This is useful for exhaustive testing or processing. ```motoko import Iter "mo:core/Iter"; let iter = Nat16.allValues(); assert iter.next() == ?0; assert iter.next() == ?1; assert iter.next() == ?2; // ... ``` -------------------------------- ### Motoko Client Instantiation and Usage Source: https://github.com/caffeinelabs/motoko/blob/master/doc/overview-slides.md Instantiates multiple 'Client' actors and starts them by providing their names and a 'Server' instance. This demonstrates how to set up and initiate communication between clients and a server. ```motoko let bob = Client(); let alice = Client(); let charlie = Client(); bob.start("Bob", Server); alice.start("Alice", Server); charlie.start("Charlie", Server); ``` -------------------------------- ### Map Creation, Insertion, Retrieval, and Removal Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Map.md Demonstrates the basic usage of the `Map` including creation, insertion, retrieval, and removal of key-value pairs. Requires importing `Map` and `Nat` modules. ```motoko import Map "mo:core/Map"; import Nat "mo:core/Nat"; persistent actor { // creation let map = Map.empty(); // insertion Map.add(map, Nat.compare, 0, "Zero"); // retrieval assert Map.get(map, Nat.compare, 0) == ?"Zero"; assert Map.get(map, Nat.compare, 1) == null; // removal Map.remove(map, Nat.compare, 0); assert Map.isEmpty(map); } ``` -------------------------------- ### Motoko Object with Public and Private Functions Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/1-basic-syntax/8-functions.md In objects, modules, and actors, functions are private by default. This example shows an object 'Counter' with private 'value' and 'reset', and public 'inc' and 'get' methods. ```motoko object Counter { var value = 0; func reset() { value := 0 }; public func inc() { value := 1}; public func get() : Nat { value }; } ``` -------------------------------- ### Importing and Using Core Types Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Types.md Demonstrates how to import and use Result and Iter types for error handling and sequence iteration. ```motoko import { type Result; type Iter } "mo:core/Types"; // Result for error handling let result : Result = #ok(42); // Iterator for sequences let iter : Iter = { next = func() { ?1 } }; ``` -------------------------------- ### Queue Construction and Basic Operations Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/pure/Queue.md Demonstrates how to create an empty queue, check if it's empty, and add a single element. ```APIDOC ## Function `empty` ### Description Create a new empty queue. ### Signature ```motoko func empty() : Queue ``` ### Example ```motoko import Queue "mo:core/pure/Queue"; persistent actor { let queue = Queue.empty(); assert Queue.isEmpty(queue); } ``` ### Runtime `O(1)` ### Space `O(1)` ## Function `isEmpty` ### Description Determine whether a queue is empty. Returns true if `queue` is empty, otherwise `false`. ### Signature ```motoko func isEmpty(self : Queue) : Bool ``` ### Example ```motoko import Queue "mo:core/pure/Queue"; persistent actor { let queue = Queue.empty(); assert Queue.isEmpty(queue); } ``` ### Runtime `O(1)` ### Space `O(1)` ## Function `singleton` ### Description Create a new queue comprising a single element. ### Signature ```motoko func singleton(item : T) : Queue ``` ### Example ```motoko import Queue "mo:core/pure/Queue"; persistent actor { let queue = Queue.singleton(25); assert Queue.size(queue) == 1; } ``` ### Runtime `O(1)` ### Space `O(1)` ``` -------------------------------- ### Remove Entry and Get Value from TrieMap Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/base/TrieMap.md Remove an entry from the TrieMap by key and return the removed value. Returns null if the key was not found. The example shows removing an entry and retrieving its value. ```motoko map.put(0, 10); map.remove(0) ``` -------------------------------- ### Create and Populate RBTree Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/base/RBTree.md Demonstrates how to create a new RBTree instance with a custom comparison function and insert key-value pairs. Imports for RBTree, Nat, and Debug are required. ```motoko import RBTree "mo:base/RBTree"; import Nat "mo:base/Nat"; import Debug "mo:base/Debug"; let tree = RBTree.RBTree(Nat.compare); // Create a new red-black tree mapping Nat to Text tree.put(1, "one"); tree.put(2, "two"); tree.put(3, "tree"); for (entry in tree.entries()) { Debug.print("Entry key=" # debug_show(entry.0) # " value=\"" # entry.1 #"""); } ``` -------------------------------- ### Motoko preupgrade() function for saving state Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/icp-features/6-system-functions.md Example of the preupgrade() system function saving a HashMap of user balances into a stable variable before a canister upgrade. This function is invoked before the new Wasm module is installed. ```Motoko import Iter "mo:core/Iter"; import HashMap "mo:base/HashMap"; // Data structure from original standard library persistent actor Token { transient var balances = HashMap.HashMap(10, Text.equal, Text.hash); // Non-stable var savedBalances : [(Text, Nat)] = []; // Implicit stable storage system func preupgrade() { savedBalances := Iter.toArray(balances.entries()); // Save state before upgrade } } ``` -------------------------------- ### Create a Singleton PriorityQueue Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/PriorityQueue.md Demonstrates creating a priority queue with a single element using the `singleton` function and peeking at that element. ```motoko import PriorityQueue "mo:core/PriorityQueue"; let pq = PriorityQueue.singleton(42); assert PriorityQueue.peek(pq) == ?42; ``` -------------------------------- ### Motoko Actor with Shared Functions Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/1-basic-syntax/8-functions.md This example demonstrates an actor 'Digit' with public 'shared' functions. 'inc' modifies state, while 'get' is a 'shared query' for read-only access. Shared functions provide caller identity. ```motoko persistent actor Digit { var value = 0; func reset() { value := 0 }; public shared func inc() : async (){ value += 1; if (value == 10) reset(); }; public shared query func get() : async Nat { value }; } ``` -------------------------------- ### Motoko Enhanced Migration Example: Initial Deployment Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/2-actors/4-compatibility.md Represents the stable signature after an initial deployment with one migration ('00_Init'). The signature includes the migration chain and the final stable fields. ```json // Version: 4.0.0 { "00_Init" : {} -> {a : Nat} } actor { stable a : Nat } ``` -------------------------------- ### Get Value by Key in Motoko Map Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Map.md Retrieve the value associated with a given key. Returns null if the key is not found. This is an O(log(n)) operation. The example shows retrieving an existing value and handling a non-existent key. ```motoko import Map "mo:core/Map"; import Nat "mo:core/Nat"; persistent actor { let map = Map.fromIter( [(0, "Zero"), (1, "One"), (2, "Two")].values(), Nat.compare); assert Map.get(map, Nat.compare, 1) == ?"One"; assert Map.get(map, Nat.compare, 3) == null; } ``` -------------------------------- ### Get Performance Counter Value Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/InternetComputer.md Retrieve the current value of a specified Internet Computer performance counter. Counter 0 measures instructions since the start of the current message or await, while Counter 1 measures instructions within the current call context, excluding nested calls for replicated messages. ```motoko import IC "mo:core/InternetComputer"; let c1 = IC.performanceCounter(1); // ... let diff : Nat64 = IC.performanceCounter(1) - c1; ``` -------------------------------- ### Run mo-doc with default options Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/motoko-tooling/3-mo-doc.md Executes mo-doc to generate HTML documentation from the default source directory (`src`) to the default output directory (`docs`). ```bash $(dfx cache show)/mo-doc [options] ``` ```bash $(dfx cache show)/mo-doc ``` ```bash mo-doc ``` -------------------------------- ### Install Canpack CLI Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/motoko-tooling/1-canpack.mdx Install the Canpack command-line interface using npm. Ensure Node.js and npm are installed. ```bash npm install -g canpack ``` -------------------------------- ### Safely Get Element by Index (get) Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/List.md The get function returns the element at a specific zero-based index as an option. It returns null if the index is out of bounds. This function is deprecated. ```motoko let list = List.empty(); List.add(list, 10); List.add(list, 11); assert List.get(list, 0) == ?10; assert List.get(list, 2) == null; ``` -------------------------------- ### Run Python HTTP Server for Browser Tests Source: https://github.com/caffeinelabs/motoko/blob/master/test/README.md Start a Python 3 HTTP server to serve test files for browser execution. The script parses the directory listing, so this specific command is recommended. ```shell python3 -m http.server ``` -------------------------------- ### Initialize an empty Trie Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/base/Trie.md Demonstrates how to create an empty Trie and set up type aliases for convenience. This is the starting point for building a Trie. ```motoko import { print } from "mo:base/Debug"; import Trie "mo:base/Trie"; import Text "mo:base/Text"; // we do this to have shorter type names and thus // better readibility type Trie = Trie.Trie; type Key = Trie.Key; // We have to provide `put`, `get` and `remove` with // a function of return type `Key = { hash : Hash.Hash; key : K }` func key(t: Text) : Key { { hash = Text.hash t; key = t } }; // We start off by creating an empty `Trie` var trie : Trie = Trie.empty(); ``` -------------------------------- ### Get Principal from Actor in Motoko Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/base/Principal.md Use Principal.fromActor to get the Principal identifier of an actor. ```motoko actor MyCanister { func getPrincipal() : Principal { let principal = Principal.fromActor(MyCanister); } } ``` -------------------------------- ### Map Creation, Insertion, Retrieval, and Removal Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/pure/Map.md Demonstrates the basic operations of creating an empty map, inserting key-value pairs, retrieving values by key, and removing entries. Ensure the compare function is consistent across operations. ```motoko import Map "mo:core/pure/Map"; import Nat "mo:core/Nat"; persistent actor { // creation let empty = Map.empty(); // insertion let map1 = Map.add(empty, Nat.compare, 0, "Zero"); // retrieval assert Map.get(empty, Nat.compare, 0) == null; assert Map.get(map1, Nat.compare, 0) == ?"Zero"; // removal let map2 = Map.remove(map1, Nat.compare, 0); assert not Map.isEmpty(map1); assert Map.isEmpty(map2); } ``` -------------------------------- ### Getting Text Size Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Text.md Shows how to get the number of characters in a Text value using Text.size. ```motoko let size = Text.size("abc"); assert size == 3; ``` -------------------------------- ### Check if Text Starts With a Pattern Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Text.md Returns true if the Text starts with a prefix matching the specified Pattern. ```motoko assert Text.startsWith("Motoko", #text "Mo"); ``` -------------------------------- ### Create an Empty PriorityQueue Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/PriorityQueue.md Shows how to create an empty priority queue using the `empty` function and verify it is empty. ```motoko import PriorityQueue "mo:core/PriorityQueue"; let pq = PriorityQueue.empty(); assert PriorityQueue.isEmpty(pq); ``` -------------------------------- ### Trim Pattern from Start of Text Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/base/Text.md Trims all occurrences of a pattern from the start of a text. Use `stripStart` for a single occurrence. ```motoko let trimmed = Text.trimStart("---abc", #char '-') // "abc" ``` -------------------------------- ### Create and Use a Pure Set Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/pure/Set.md Demonstrates creating a pure set from an iterator, checking its size, and verifying element containment and set difference. Requires importing Set and Nat modules. ```motoko import Set "mo:core/pure/Set"; import Nat "mo:core/Nat"; persistent actor { let set = Set.fromIter([3, 1, 2, 3].values(), Nat.compare); assert Set.size(set) == 3; assert not Set.contains(set, Nat.compare, 4); let diff = Set.difference(set, set, Nat.compare); assert Set.isEmpty(diff); } ``` -------------------------------- ### rangeInclusive Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Nat.md Generates an iterator over integers from a start to an end value, inclusive. Returns an empty iterator if the start is greater than the end. ```APIDOC ## Function `rangeInclusive` ``` motoko no-repl func rangeInclusive(from : Nat, to : Nat) : Iter.Iter ``` ### Description Returns an iterator over the integers from the first to second argument, inclusive. If the first argument is greater than the second argument, the function returns an empty iterator. ### Parameters * `from` (Nat) - The starting value of the range. * `to` (Nat) - The ending value of the range. ### Returns An iterator (`Iter.Iter`) over the specified range of Nat values. ``` -------------------------------- ### Counter Actor Example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/2-actors/1-actors-async.md An example actor that manages a mutable counter state using asynchronous functions for incrementing and reading. ```motoko actor Counter { var count : Nat = 0; public shared func inc() : async () { count += 1; }; public shared func read() : async Nat { return count; }; public shared func bump() : async Nat { count += 1; return count; }; } ``` -------------------------------- ### Motoko: Compile with Invariant Type Parameters Source: https://github.com/caffeinelabs/motoko/blob/master/Changelog.md This example demonstrates Motoko code that now compiles due to improved handling of invariant type parameters. It shows how the compiler can infer type arguments when a principal solution exists. ```motoko import VarArray "mo:core/VarArray"; let varAr = [var 1, 2, 3]; let result = VarArray.map(varAr, func x = x : Int); ``` -------------------------------- ### Alternative Switch Implementation for Get Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/3-types/10-options.md An alternative implementation of the get function using a switch expression. This shows the more verbose but equivalent logic. ```motoko func get(option : ?T, defaultValue : T) : T { switch option { case null defaultValue; case (?value) value; } }; ``` -------------------------------- ### Function init3 Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/internal/PRNG.md Initializes the PRNG state with three state variables. ```APIDOC ## Function `init3` ### Description Initializes the PRNG state with three state variables. ### Signature ```motoko no-repl func init3(seed1 : Nat64, seed2 : Nat64, seed3 : Nat64) ``` ``` -------------------------------- ### Get Absolute Value of an Int Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Int.md Use the `abs` function to get the absolute value of an integer. Requires the Int module to be imported. ```motoko assert Int.abs(-12) == 12; ``` -------------------------------- ### Importing Specific Functions from a Module Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/4-declarations/7-module-declarations.md This Motoko example shows how to import specific functions ('init' and 'identity') directly from the 'Matrix' module using pattern matching in the import statement, avoiding dot notation. ```motoko import {init; identity} "Matrix"; let zero = init(3, 3, 0); let id4 = identity(4); ``` -------------------------------- ### Nat16.rangeInclusive Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Nat16.md Returns an iterator over Nat16 values from a start (inclusive) to an end (inclusive). If the start is greater than the end, an empty iterator is returned. ```APIDOC ## Function `rangeInclusive` ### Description Returns an iterator over `Nat16` values from the first to second argument, inclusive. If the first argument is greater than the second argument, the function returns an empty iterator. ### Signature ```motoko func rangeInclusive(from : Nat16, to : Nat16) : Iter.Iter ``` ### Example ```motoko import Iter "mo:core/Iter"; let iter = Nat16.rangeInclusive(1, 3); assert iter.next() == ?1; assert iter.next() == ?2; assert iter.next() == ?3; assert iter.next() == null; let emptyIter = Nat16.rangeInclusive(4, 1); assert emptyIter.next() == null; ``` ``` -------------------------------- ### Motoko Set.join Example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/pure/Set.md Demonstrates how to use Set.join to combine multiple sets into a single union set. Ensure all sets are ordered by the same comparison function. ```motoko import Set "mo:core/pure/Set"; import Nat "mo:core/Nat"; import Iter "mo:core/Iter"; persistent actor { let set1 = Set.fromIter([1, 2, 3].values(), Nat.compare); let set2 = Set.fromIter([3, 4, 5].values(), Nat.compare); let set3 = Set.fromIter([5, 6, 7].values(), Nat.compare); let combined = Set.join([set1, set2, set3].values(), Nat.compare); assert Iter.toArray(Set.values(combined)) == [1, 2, 3, 4, 5, 6, 7]; } ``` -------------------------------- ### Character Literals and Basic Usage Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Char.md Demonstrates creating Char literals, including Unicode characters, and using basic Char functions like isDigit and toText. Requires importing the Char module. ```motoko let char : Char = 'A'; let unicodeChar = '漢'; let digit = '7'; assert Char.isDigit(digit); assert Char.toText(char) == "A"; ``` -------------------------------- ### Nat16.range Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Nat16.md Returns an iterator over Nat16 values from a start (inclusive) to an end (exclusive). If the start is greater than the end, an empty iterator is returned. ```APIDOC ## Function `range` ### Description Returns an iterator over `Nat16` values from the first to second argument with an exclusive upper bound. If the first argument is greater than the second argument, the function returns an empty iterator. ### Signature ```motoko func range(fromInclusive : Nat16, toExclusive : Nat16) : Iter.Iter ``` ### Example ```motoko import Iter "mo:core/Iter"; let iter = Nat16.range(1, 4); assert iter.next() == ?1; assert iter.next() == ?2; assert iter.next() == ?3; assert iter.next() == null; let emptyIter = Nat16.range(4, 1); assert emptyIter.next() == null; ``` ``` -------------------------------- ### Get Blob Size Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Blob.md Illustrates how to get the number of bytes in a Blob using both the `size` function and the `blob.size()` method. Both methods return the same result. ```motoko let blob = "\FF\00\AA" : Blob; assert Blob.size(blob) == 3; assert blob.size() == 3; ``` -------------------------------- ### Importing the Text Module Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Text.md Shows how to import the Text module from the core package to access its utility functions. ```motoko import Text "mo:core/Text"; ``` -------------------------------- ### Reusable view mixin example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/icp-features/7-view-queries.md Demonstrates how to include a view mixin in an actor to automatically generate view queries for common data structures like Map.Map. ```motoko import Views "views"; persistent actor { include Views(); let customers : Map.Map = Map.empty(); // __customers query is auto-generated using MapView.view }; ``` -------------------------------- ### Initialize TrieMap Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/base/TrieMap.md Instantiate a TrieMap with custom equality and hash functions. This example uses Nat.equal and Hash.hash for Nat keys and values. ```motoko import TrieMap "mo:base/TrieMap"; import Nat "mo:base/Nat"; import Hash "mo:base/Hash"; import Iter "mo:base/Iter"; let map = TrieMap.TrieMap(Nat.equal, Hash.hash) ``` -------------------------------- ### Get a value from an OrderedMap Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/base/OrderedMap.md Use `get` to retrieve the value associated with a specific key. It returns the value if the key exists, otherwise it returns null. ```motoko import Map "mo:base/OrderedMap"; import Nat "mo:base/Nat"; import Iter "mo:base/Iter"; import Debug "mo:base/Debug"; let natMap = Map.Make(Nat.compare); let map = natMap.fromIter(Iter.fromArray([(0, "Zero"), (2, "Two"), (1, "One")])) Debug.print(debug_show(natMap.get(map, 1))); Debug.print(debug_show(natMap.get(map, 42))); // ?"One" // null ``` -------------------------------- ### Int16.rangeInclusive Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Int16.md Returns an iterator over Int16 values from an inclusive start to an inclusive end. If the start value is greater than the end value, an empty iterator is returned. ```APIDOC ## Function `rangeInclusive` ``` motoko no-repl func rangeInclusive(from : Int16, to : Int16) : Iter.Iter ``` Returns an iterator over `Int16` values from the first to second argument, inclusive. ```motoko include=import import Iter "mo:core/Iter"; let iter = Int16.rangeInclusive(1, 3); assert iter.next() == ?1; assert iter.next() == ?2; assert iter.next() == ?3; assert iter.next() == null; ``` If the first argument is greater than the second argument, the function returns an empty iterator. ```motoko include=import import Iter "mo:core/Iter"; let iter = Int16.rangeInclusive(4, 1); assert iter.next() == null; // empty iterator ``` ``` -------------------------------- ### Switch Statement with Option Types Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/5-control-flow/5-switch.md Demonstrates how to handle Option types using switch statements, checking for Some and None values. ```motoko actor { public func processOption(o : ?Nat) : Nat { switch o { case ?x => x case null => 0 } } } ``` -------------------------------- ### Int16.range Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Int16.md Returns an iterator over Int16 values from an inclusive start to an exclusive end. If the start value is greater than the end value, an empty iterator is returned. ```APIDOC ## Function `range` ``` motoko no-repl func range(fromInclusive : Int16, toExclusive : Int16) : Iter.Iter ``` Returns an iterator over `Int16` values from the first to second argument with an exclusive upper bound. ```motoko include=import import Iter "mo:core/Iter"; let iter = Int16.range(1, 4); assert iter.next() == ?1; assert iter.next() == ?2; assert iter.next() == ?3; assert iter.next() == null; ``` If the first argument is greater than the second argument, the function returns an empty iterator. ```motoko include=import import Iter "mo:core/Iter"; let iter = Int16.range(4, 1); assert iter.next() == null; // empty iterator ``` ``` -------------------------------- ### Motoko: Dubious Code Example with Unused Identifier Source: https://github.com/caffeinelabs/motoko/blob/master/src/lang_utils/error_codes/M0194.md This example shows a Motoko identifier 'nickname' that is defined but never used, triggering the M0194 warning. ```motoko let nickname = "klutz"; // code that never uses `nickname` ``` -------------------------------- ### Instantiate and Test Actor Class Counter Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/fundamentals/4-declarations/4-class-declarations.md Demonstrates creating an instance of the Counter actor class from another file, calling its methods, and printing the results. Requires provisioning cycles for constructor calls. ```motoko import Counter "./Counter"; persistent actor { public func test() : async () { let counter = await (with cycles = 1_000_000_000_000) Counter.Counter(0); let newCount = await counter.inc(); Debug.print("Count is now: " # Nat.toText(newCount)); let currentCount = await counter.get(); Debug.print("Current count: " # Nat.toText(currentCount)); }; } ``` -------------------------------- ### Map Comparison Example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/pure/Map.md Compares two maps using Nat for keys and Text for values. Asserts the expected comparison result (#less, #equal, #greater). Requires importing Map, Nat, and Text modules. ```motoko import Map "mo:core/pure/Map"; import Nat "mo:core/Nat"; import Text "mo:core/Text"; persistent actor { let map1 = Map.fromIter([(0, "Zero"), (1, "One")].values(), Nat.compare); let map2 = Map.fromIter([(0, "Zero"), (2, "Two")].values(), Nat.compare); assert Map.compare(map1, map2, Nat.compare, Text.compare) == #less; assert Map.compare(map1, map1, Nat.compare, Text.compare) == #equal; assert Map.compare(map2, map1, Nat.compare, Text.compare) == #greater } ``` -------------------------------- ### Motoko Test File with Drun Calls Source: https://github.com/caffeinelabs/motoko/blob/master/test/README.md Example of specifying additional calls for `drun` using `//CALL` and `//OR-CALL` comments. ```motoko //CALL //OR-CALL ``` -------------------------------- ### Motoko Variable Array Mapping Example Source: https://github.com/caffeinelabs/motoko/blob/master/Changelog.md Example demonstrating the `VarArray.map` function with a mutable array. The `debug_show` function is used to display the mapped values. ```motoko import VarArray "mo:core/VarArray"; let varAr = [var 1, 2, 3]; let result = VarArray.map(varAr, func x = debug_show (x) # "!"); // [var Text] ``` -------------------------------- ### Build Motoko Tests with Nix Source: https://github.com/caffeinelabs/motoko/blob/master/test/README.md Use this command to build the entire Motoko test suite via Nix. Ensure you are in the top-level Motoko directory. ```shell $ nix-build -A tests ``` -------------------------------- ### Get Element by Position Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Stack.md Use `get` to retrieve an element at a specific position from the top (0-indexed). Returns null if the position is out of bounds. This operation is linear time. ```motoko import Stack "mo:core/Stack"; persistent actor { let stack = Stack.empty(); Stack.push(stack, 'c'); Stack.push(stack, 'b'); Stack.push(stack, 'a'); assert Stack.get(stack, 0) == ?'a'; assert Stack.get(stack, 1) == ?'b'; assert Stack.get(stack, 2) == ?'c'; assert Stack.get(stack, 3) == null; } ``` -------------------------------- ### Motoko Set Difference Example Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Set.md Shows how to compute the difference between two sets (set1 minus set2). Ensure Set, Nat, and Iter modules are imported and a comparison function is supplied. ```motoko import Set "mo:core/Set"; import Nat "mo:core/Nat"; import Iter "mo:core/Iter"; persistent actor { let set1 = Set.fromIter([1, 2, 3].values(), Nat.compare); let set2 = Set.fromIter([3, 4, 5].values(), Nat.compare); let difference = Set.difference(set1, set2, Nat.compare); assert Iter.toArray(Set.values(difference)) == [1, 2]; } ``` -------------------------------- ### Get Canister Environment Variable Value Source: https://github.com/caffeinelabs/motoko/blob/master/doc/md/core/Runtime.md Use `Runtime.envVar` to get the optional value of a specific canister environment variable by its name. Traps if the variable is unknown. ```motoko let value = Runtime.envVar("MY_ENV_VAR"); let result = switch (value) { case (?v) v; case null Runtime.trap("Unknown environment variable"); }; ```