F# discriminated union syntax clarification

半城伤御伤魂 提交于 2019-12-20 01:13:52

问题


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 * 'T list

Although I understand conceptually what's going on here, I do not understand the syntax. Apparently you can put [] or :: between parentheses and they mean something special.

Other symbols aren't allowed, for example (++) or (||). So what's going on here?

And another thing is the 'operator' nature of (::). Suppose I have the following (weird) type:

type 'T X =
    | None
    | Some of 'T * 'T X
    | (::) of 'T * 'T X

Now I can say:

let x: X<string> = Some ("", None)

but these aren't allowed:

let x: X<string> = :: ("", None)
let x: X<string> = (::) ("", None)

So (::) is actually something completely different than Some, although both are cases in a discriminated union.


回答1:


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.



来源:https://stackoverflow.com/questions/40270879/f-discriminated-union-syntax-clarification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!