Type erasure in Swift
swift
Heavyweight pattern: type-erasure of PATs
- Requires three auxiliary types
- Abstract box type
- If protocol: it’s okay I guess
- If class: need abstract class fatalError stubs
- Concrete box type
- Forwarding shims
- User-facing
AnyXXX
type- Stores an abstract box, implemented as a concrete box
- Abstract box type
Possible to type-erase generic parameters?
- Seems hard if you try to store it, can’t do
TensorN<Shape = _, Scalar = _>
- But wait… possible with closures! Introducing closure-based type erasure
Closure fusion
Demonstrates successful optimization across composition of type-erased calculations using functions..
https://gist.github.com/dabrahams/a44a2a078d8556ef9c2ff2c56e83e62a
- Note: closures are like
callAsMethod
function. This works best for types that have one main purpose: e.g. tensors are indexers, functions like+
can be implemented in this paradigm. - There is some relation to closures vs objects. Check out the Koan: https://wiki.c2.com/?ClosuresAndObjectsAreEquivalent
Type erasure survey
https://gist.github.com/dabrahams/c75760b7ed36dd4f039f3679ede825ea