What does this '()' notation mean?

后端 未结 4 1045
猫巷女王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:43

    Definitely do NOT think of () as some syntax for a function call or anything like that. It's just a value, like 3, 5, 'q', false, or "blah". It happens to be a value of type Unit, and in fact it's the only value of type unit, but really that's beside the point. () here is just a value. I can't stress that enough.

    First consider

    let name x = 3
    

    What's this? This just defines a function on x, where x can be any type. In C# that would be:

    int Name(T x) 
    {
        return 3;
    }
    

    Now if we look at let name () = 3 (and I somewhat recommend putting that extra space there, so it makes () look more a value than some syntactic structure) then in C# you can think of it as something like (pseudocode)

    int Name(T x) where T == Unit  //since "()" is the only possible value of Unit
    {
        return 3;
    }
    

    or, more simply

    int Name(Unit x)
    {
        return 3;
    }
    

    So we see that all let name () = 3 is, the definition of a function that takes a Unit argument, and returns 3, just like the C# version above.

    However if we look at let name = 3 then that's just a variable definition, just like var name = 3 in C#.

提交回复
热议问题