Values in Unison are not, by default, lazily evaluated. But it's common to want to express that a value or calculation should be delayed until it's absolutely needed.
For example the term
longTextin the following snippet is evaluated strictly:
But you might not actually need to evaluate
longText--thereare circumstances where the calculation of a value might be very expensive or could introduce surprising behavior if runeagerly.
One way you might solve for this is to create a "thunk": a function with no arguments which returns the desired value or computation when it's called.
longText : () -> Text longText _ = "🐵 Imagine infinite monkeys on infinite typewriters 🙊…"
Because this is a common pattern, Unison provides the single quote,
',as syntactic sugar for representing a function with the form
() -> a.
We can rewrite
() -> Textas just
When we want to run the thunk, we could call the value with
()to represent "I'm calling this with zero arguments", but Unison also provides syntactic sugar for "forcing" or calling a thunk with the
Calling our function
Simple enough… single quote,
',introduces athunkand the bang symbol,
!,executes it, but what if we want to call
coinflipwith an argument
trueand then return the result of that function application in a thunk? Our final desired return type is
'Text.To do that, we have to surround the function application for
coinflip truein parentheses before prepending the single quote symbol.
Eager evaluation means that values and expressions are evaluated as soon as they are bound to a variable, as opposed to when they are called.
A thunk is a function which takes no arguments and returns a value. Its type is:
() -> aand it's used to delay calculating a value until "forced" or evaluated.