문제

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
        }
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top