F# 试图创建一个更好的 printf

标签 f# unit-type

我正在尝试创建一个可以打印任何类型的打印语句。我想使用类型模式匹配来实现这一点。

这行不通:

let print x = match x with | :? int -> printf "INT"; | _ -> None;;

我收到消息:

let print x = match x with | :? int -> printf "INT"; | _ -> None;;
-----------------------------^^^^^^

stdin(47,30): error FS0008: This runtime coercion or type test from type 'a to int involves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed.

所以,我不能对 int 进行类型匹配?我不能对哪些其他类型进行类型匹配?需要进一步的类型注释是什么意思?

最佳答案

类型测试仅针对引用类型进行。因此:

let print x = 
    match box x with 
    | :? int -> printf "INT"
    | _ -> ()

let print (x: obj) = 
    match x with 
    | :? int -> printf "INT"
    | _ -> ()

会起作用。

请注意,您的函数不进行类型检查,因为 None 属于 option 类型,这与 printf 的 unit 类型不同“INT”

关于F# 试图创建一个更好的 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9827323/

相关文章:

f# - Json Provider 可以反序列化为 Generic.Dictionary 吗?

static - 有区别的联合方法看不到它的静态成员

f# - 如何从 f# 中的表达式返回单位

f# - 我可以在 F# 成员函数上指定函数类型吗?

types - "This expression was expected to have type unit"但我希望它是 bool 值

f# - 可选地获取序列中的第一项

F# 按类型进行模式匹配

c# - 如何在 F# 中定义 T[] 的类型扩展?

F# 在 If/Then 中推断类型

f# - 此表达式的类型应该为 'unit',但类型为 'ConsoleKeyInfo'