I wanna share a technique for managing an incremental collection in sodium.
The reader might be familiar with derivatives from calculus at school. It turns out derivatives do not only apply to equations that can be evaluated to a numerical value. Derivatives apply to other things too, in other fields.
In incremental calculus, the derivative of a type signature that represents a value is the type signature of a representation of the change of that value (think Array
from 1st post, its derivative is ArrayChanges
).
So here is something I've found very handy:
If f(x) = Cell<g(x)>
, then the derivative f'(x) = Stream<g'(x)>
. It sort of feels like the chain-rule.
Note: Above is a this is a type-level derivative, not a value-level derivative.
How is this useful? Watch this:
OK. We want to manage this list incrementally:
Cell<List<Tuple<Integer,Foo>>>
,
The Integer
here is just an ID number for easy removal of existing Foo
s.
Now Foo
has attributes that are also represented by sodium objects too internally. That way each element of our UI can independently be hooked up to each Foo
independently, and be updated independently without regenerating the whole UI. But what if Foo
s are added or removed from this list? We do not want to regenerate the whole UI again. So this is where the derivative comes into play.
let f = Cell<List<Tuple<Integer,Foo>>>
now:
f' = Stream<Tuple<List<Tuple<Integer,Foo>>,List<Integer>>>
In the change structure above I'm just focusing on Foo
s added in the 1st part of the tuple, then a list of Foo
IDs in the 2nd part of the tuple for Foo
s that are removed. Now using that f
for the initial construction of the UI, then using f'
for changing UI elements that get added/removed, you now have a completely incremental UI for elements added/removed or changed in place. Only the parts of the UI that are required to be updated will be updated, and the whole UI will not be recalcuated from scratch.
I had a really good run with sodium today at work. I used the technique described above for a custom paperwork creator that allows dragging in viewport of the 3d scene on some paper and adding labels and dimensions on top in paper space. It worked like a dream, all UI elements where updated completely incrementally. So I wanted to share.
Sodium is a truly wonderful language.