f# - "as"和指定类型的冒号之间的区别?

标签 f#

我最初认为“as”和冒号运算符的含义完全相同,用于指定值或函数的类型。但我实际上发现了一个不一致的地方:

type Uppercase = string -> string
let uppercase:Uppercase = fun n ->
    //code

这很好用。但是如果我将冒号更改为“as”

type Uppercase = string -> string
let uppercase as Uppercase = fun n ->
    //code

它崩溃了,说它不知道“n”是什么类型。当然,我可以通过这样做来解决这个问题

type Uppercase = string -> string
let uppercase as Uppercase = fun (n:string) ->
    //code

又开心了。所以,我的问题是,为什么“as”与冒号不同,为什么 F# 在使用“as”时似乎无法进行类型推断?谢谢。

最佳答案

as 用于命名模式匹配的结果,例如

let (a,b) as t = (1,2)

会将 a 绑定(bind)到 1,将 b 绑定(bind)到 2,将 t 绑定(bind)到整个对。因此

let uppercase as Uppercase = fun n -> ...

将名称 uppercaseUppercase 绑定(bind)到函数。在此函数中,未指定 n 的类型,因此您会收到类型错误。

as 因此与显式类型声明有很大不同,并且不能互换使用。

关于f# - "as"和指定类型的冒号之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33128600/

相关文章:

asynchronous - 条件为 async 的异步计算表达式中的 'while'

c# - 在 f# 中实现接口(interface)

.net - F#中类型的最大值/最小值

f# - "Language Oriented Programming"与现实世界中的 OOP/Functional 相比如何

asynchronous - 取消的任务不会将控制权返回给异步 block

F#接口(interface)继承失败,由于单元

f# - 相当于重复的 takeWhile 调用 : does this function have a "standard" name?

haskell - 在 Haskell 中实现 FSharp 的 Int32.TryParse

list - F# - 使用 List.foldBack 将整数列表拆分为奇数和偶数

f# - 在F#中使用StringBuilder是否正确?