【发布时间】:2017-01-23 19:31:54
【问题描述】:
在玩过 Idris 之后,我已经成为使用 显式类型 来加强我的 F# 程序的声明式自我文档的超级粉丝,方法是更频繁地在我的函数上显式地编写类型,并通过使用类型别名。
用显式类型定义我的函数让我(重新)发现 F# 实际上有两种函数显式类型。有使用 : 的标准 let 函数样式,还有使用 -> 的 lambda 函数。
例如
// explicitly typed function using the classical let ':' style
let OK1 (content : string) (context : Context) : Async<Context option> =
{ context with Response = { Content = content; StatusCode = 200 } }
|> Some
|> async.Return
// explicitly typed function using the '->' style
let OK2 : string -> Context -> Async<Context option> = fun content context ->
{ context with Response = { Content = content; StatusCode = 200 } }
|> Some
|> async.Return
-> 样式的好处是我可以定义类型别名,例如
// type alias defining a webpart
type WebPart = Context -> Async<Context option>
// using the type alias in the declaration of an explicitly typed function
let OK2 : string -> WebPart = fun content context ->
{ context with Response = { Content = content; StatusCode = 200 } }
|> Some
|> async.Return
我认为不可能用: 样式声明和使用相同的类型别名...?
我很困惑为什么 F# 有两种在函数上声明显式类型的风格。这是某种.Net限制吗?还是有什么特殊用途? 为什么不用-> 而不是: 来定义所有显式类型?
【问题讨论】:
标签: f#