F# discriminated union syntax clarification

前端 未结 1 1244
醉梦人生
醉梦人生 2021-01-19 15:33

I\'m reading Expert F# 4.0 and at some point (p.93) the following syntax is introduced for list:

type \'T list =
    | ([])
    | (::) of \'T *          


        
相关标签:
1条回答
  • 2021-01-19 16:18

    Theoretically, F# spec (see section 8.5) says that union case identifiers must be alphanumeric sequences starting with an upper-case letter.

    However, this way of defining list cons is an ML idiomatic thing. There would be riots in the streets if we were forced to write Cons (x, Cons(y, Cons (z, Empty))) instead of x :: y :: z :: [].

    So an exception was made for just these two identifiers - ([]) and (::). You can use these, but only these two. Besides these two, only capitalized alphanumeric names are allowed.

    However, you can define free-standing functions with these funny names:

    let (++) a b = a * b
    

    These functions are usually called "operators" and can be called via infix notation:

    let x = 5 ++ 6   // x = 30
    

    As opposed to regular functions that only support prefix notation - i.e. f 5 6.

    There is a separate quite intricate set of rules about which characters are allowed in operators, which can be only unary, which can be only binary, which can be both, and how they define the resulting operator precedence. See section 4.1 of the spec or here for full reference.

    0 讨论(0)
提交回复
热议问题