Skip to content

Instantly share code, notes, and snippets.

@matthewhammer
Created July 26, 2021 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewhammer/fb1844566acc7a52d82b8e610d429ae4 to your computer and use it in GitHub Desktop.
Save matthewhammer/fb1844566acc7a52d82b8e610d429ae4 to your computer and use it in GitHub Desktop.
Recursively `class`-`func` definitions in Motoko.
// Recursion via "manual back-patching"
//
// What?
// MyClass is defined recursively with myFunc, which refer to each other.
//
// How?
// The myClass method uses a variable for mutable storage (myClass_) to
// determine if the initialization has occured yet or not.
class Test() {
type Init = { boom : () -> ()};
class MyClass(init : Init) {
let y = init.boom;
public func bap() {
y()
};
};
var myClass_ : ?MyClass = null;
func myFunc(){ myClass().bap() };
func myClass() : MyClass {
switch myClass_ {
case null {
let x = MyClass({boom = myFunc});
myClass_ := ?x;
x
};
case (?x) x;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment