|
| 1 | +package ch03 |
| 2 | + |
| 3 | +/* |
| 4 | +codata is a product of destructors, where destructors are functions from |
| 5 | +the codata type (and, optionally, some other inputs) to some type. |
| 6 | +
|
| 7 | +In Scala we define codata as a trait, and implement it as a final class, |
| 8 | +anonymous subclass, or an object. |
| 9 | +
|
| 10 | +We have two strategies for implementing methods using codata: structural corecursion, which we can |
| 11 | +use when the result is codata, and structural recursion, which we can use when an input is codata. |
| 12 | +
|
| 13 | +Data is connected to codata via fold: any data can instead be implemented as codata with |
| 14 | +a single destructor that is the fold for that data. This is called Church encoding. |
| 15 | +The reverse is also: we can enumerate all potential pairs of inputs and outputs of |
| 16 | +destructors to represent codata as data. |
| 17 | +
|
| 18 | +Data and codata offer different forms of extensibility: data makes it easy to add |
| 19 | +new functions, but adding new elements requires changing existing code, while it is |
| 20 | +easy to add new elements to codata but we change existing code if we add new functions. |
| 21 | + */ |
| 22 | +// Polymorphic function type, new in Scala 3. |
| 23 | +// https://www.youtube.com/watch?v=sauaDZ-1-zM |
| 24 | +type List[A, B] = (B, (A, B) => B) => B |
| 25 | + |
| 26 | +// Polymorphic function of two types, A and B, that takes no arg |
| 27 | +// and returns the type defined above. |
| 28 | +val Empty: [A, B] => () => List[A, B] = |
| 29 | + // empty: B |
| 30 | + [A, B] => () => (empty, _) => empty |
| 31 | + |
| 32 | +val Pair: [A, B] => (A, List[A, B]) => List[A, B] = |
| 33 | + // empty: B, f: (A, B) => B |
| 34 | + [A, B] => (head: A, tail: List[A, B]) => (empty, f) => f(head, tail(empty, f)) |
| 35 | + |
| 36 | +val list: [B] => () => List[Int, B] = |
| 37 | + [B] => () => Pair(1, Pair(2, Pair(3, Empty()))) |
0 commit comments