2 ms·
Swift: Lazy Properties in Structs
- melling 11y agoI just started using structs in Swift within the past couple of weeks. There's actually a lot written on the topic: http://www.h4labs.com/dev/ios/swift.html?age=10000&q=structs http://www.h4labs.com/dev/ios/swift.html?age=10000&q=structs
- kazinator 11y agoI put this into TXR Lisp a few weeks ago. Well, not exactly this. Rather, quite simply, any struct can be lazily instantiated with the lnew operator. This gives you the object instance with its identity, but not yet initialized. When you touch it, then all of it materializes. (It's not a per-slot behavior, in other words.) The commit for this could almost fit on a napkin: http://www.kylheku.com/cgit/txr/commit/?id=eb483eb39fa4570d1178a3f71fb65be908fd0d01 http://www.kylheku.com/cgit/txr/commit/?id=eb483eb39fa4570d1... Circular example: two structs are constructed so they refer to each other, in a single step, by using mlet for the mutual scoping, and lnew for the construction semantics: 1> (defstruct node nil left right value) #<struct-type node> 2> (defvar circ (mlet ((a (lnew node left b value 0)) (b (lnew node right a value 1))) a)) circ 3> circ.value 0 4> circ.left.value 1 5> circ.left.right.value 0 Lazy infinite chain of nodes, each containing a higher count value than its predecessor: 1> (defstruct node () next count) #<struct-type node> 2> (defun count-chain (init) (lnew node count init next (count-chain (succ init)))) count-chain 3> (defvarl x (count-chain 0)) x 4> x.count 0 5> x.next.count 1 6> x.next.next.count 2 7> x.next.next.next.count 3 8> x.next.next.next.next.count 4 9> x.count 0 10> x.next.count 1