ifc
Duck-typed interface checking - define named method sets, check whether an object has all required callable fields, require a method set (error if not satisfied), check whether an object has any of a list of methods, require multiple interface bundles at once, and build a minimal single-method object.
Load with: use ifc
What this module does
ifc brings Go-style structural interface checking to ilusm. An
interface is just a list of required method names. ifcha tests
whether an object has all of them as callable fields (function values or fn-tagged
objects). ifcre is the asserting version - it returns the object on
success or throws an error message of your choice.
This pattern is useful for generic functions that accept any object with a
specific capability (e.g. anything with a close method) without
requiring inheritance.
Quick example
use ifc
# Define an interface (a list of required method names)
Closeable = ifcme(["close"])
ReadWriteable = ifcme(["read", "write"])
# Check
conn = {read: \(n) "...", write: \(s) nil, close: \() nil}
prn(ifcha(conn, Closeable)) # tru
prn(ifcha(conn, ReadWriteable)) # tru
# Require (errors if not satisfied)
ifcre(conn, Closeable)
# Check for any of several methods
prn(ifcha1(conn, ["flush", "close"])) # tru
# Require multiple interfaces
ifcre1(conn, [Closeable, ReadWriteable])
# Build a single-method object
obj = ifcfn("greet", \(msg) "Hello, " + msg)
Functions
Interface definition
ifcme(names)
Creates a method set from a list of method name strings. Validates that all elements are strings. Returns the list (method sets are just string lists).
Checking
ifcha(obj, mset)
Returns tru if obj has every method in mset as a callable field (function or fn-tagged value). Returns fls if obj is not an object or any method is missing/non-callable.
ifcha1(obj, names)
Returns tru if obj has at least one callable field from the names list.
Requiring
ifcre(obj, mset, msg)
Returns obj if it satisfies mset, or throws msg (default: "ifc: need mset"). Useful for asserting interface compliance at function entry points.
ifcre1(obj, msets, msg)
Requires obj to satisfy every method set in the msets list. Throws with the bundle index if any bundle is not satisfied.
Construction
ifcfn(name, fn)
Constructs a minimal object with one callable field. Useful for creating adapter objects that satisfy a single-method interface.
Notes
- Callability is checked as: the field is a function, or it is an object with a
tfield equal to"fn". - Requires
trlanderu.