我正在尝试创建一个可以打印任何类型的打印语句。我想使用类型模式匹配来实现这一点。
这行不通:
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/