Delay Evaluation with LazyBox

    Brian LonsdorfBrian Lonsdorf

    We rewrite the Box example using lazy evaulation



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    00:01 With Box, we are able to map over each function, and pass our input to output, and work-like function composition here. If we run it, we get a lowercase A here, as it goes through and trims, turns things into numbers, and whatnot.

    00:13 Now we could also define a lazybox. A lazybox will take, instead of an X, will take a G here for a function. We want to convert our value that's right there, our concrete value, to a function that will eventually return our value.

    00:27 Sometimes this is referred to as a Church encoding. What we can do here is define a map. How would that work? It takes our F, and we want to return a lazybox that has a function inside. Since this is function composition, we could quite literally just run F of G here, and have our function composition.

    00:42 Fold works the same way, except fold will not bottle it back up. It'll just run it right away, so we don't need another layer of the lazybox here. What we get from this is that none of this will actually run, if I run my node there. It will just sit here.

    00:56 In fact, we could go ahead and console.log, there we go, and see that nothing runs. Now if we bring it back, and we run fold, that's like pulling the trigger. There we are. We have the same results.

    01:08 This gives us purity by virtue of laziness. Basically, nothing happens, so we don't have any impure side effects, until the very end, when we call fold. We're pushing it all the way down to the bottom. This is how a variety of types define map, where they have a function inside them instead of a concrete value, such as promises, observables, or streams, things like this.