Question

I am curious as to what is the major significance, if any in regards to taking a unit or not in code similar to below. What are the advantages or disadvantages. To my current understanding, taking a unit will implement a function that returns a value while not taking one just simply represents the value. Looking for some clarity here.

code without Unit:

    let consumerKey = 

        // retrieve keys
        query{
            for row in db.Keys do
            select {
                consumerKey = row.ConsumerKey;
                consumerSecret = row.ConsumerSecret
            }
            exactlyOneOrDefault
        }

code with Unit:

    let consumerKey() = 

        // retrieve keys
        query{
            for row in db.Keys do
            select {
                consumerKey = row.ConsumerKey;
                consumerSecret = row.ConsumerSecret
            }
            exactlyOneOrDefault
        }
Was it helpful?

Solution

The first block of code binds a value of type query<_> to identifier consumerKey while the second binds a value of type () -> query<_> to identifier consumerKey. The second is a function which when given unit will return a value of type query<_>.

In this example, the difference between the two are explicitly captured by their signatures. In other words, the first can be obtained from the second by invoking the function value with (). In terms of runtime, the second will always return a new underlying object instance, while the first one is fixed.

In cases where the evaluation causes side effects, the same would not hold. For example in thw following:

let value1 = Guid.NewGuid()
let value2 () = Guid.NewGuid()

A value1 cannot be obtained via value2 because a different value would be returned for each invocation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top