What does this '()' notation mean?

后端 未结 4 1036
猫巷女王i
猫巷女王i 2020-12-02 01:59

I just started to learn F#. The book uses the following notation:

let name() = 3
name()

what that differs from this:

let na         


        
4条回答
  •  暖寄归人
    2020-12-02 02:34

    Using () creates a function which takes a paramter of type unit, rather than the second case which is just a simple integer.

    This is particularly important when you want to control execution of the function.

    The main difference is when you have

    let name() = 
        printfn "hello"
        1
    

    vs

    let name = 
        printfn "hello"
        1
    

    then

    let t = name + name
    

    will print "hello" once. But

    let t = (name()) + (name())
    

    will print "hello" twice.

    You have to be careful with this when considering the order in which functions are evaluated.

    Consider the following program:

    let intversion = 
        printfn "creating integer constant"
        1
    
    printfn "integer created"
    
    let funcversion() =
        printfn "executing function"
        1
    
    printfn "function created"
    
    let a = intversion + intversion
    printfn "integer calculation done"
    let b = (funcversion()) + (funcveriosn())
    printfn "function calculation done"
    

    This will print the following in order

    1. creating integer constant
    2. integer created
    3. function created
    4. integer calculation done
    5. executing function
    6. executing function
    7. function calculation done

提交回复
热议问题