在中,我可以找到F#的类型。
>sprintf;;
val it : (Printf.StringFormat<'a> -> 'a) = <fun:clo@163>如果curried函数不是泛型的,我可以用第一个参数找到curried的sprintf类型。
> sprintf "%g";;
val it : (float -> string) = <fun:it@134-16>但是如果它是泛型的,那么我就会得到值限制错误。
> sprintf "%A";;
error FS0030: Value restriction. The value 'it' has been inferred to have generic type
val it : ('_a -> string)
Either make the arguments to 'it' explicit or, if you do not intend for it to be generic, add a type annotation.我可以添加一个类型注释来摆脱像这样的值限制,专门化一个类型的函数,例如。DateTime。
>let f : (DateTime -> string) = sprintf "%A";;
val f : (DateTime -> string)如何在没有绑定的情况下添加类型批注?我试过以下几种方法……
>sprintf "%A" : (DateTime -> string);;
error FS0010: Unexpected symbol ':' in interaction. Expected incomplete structured construct at or before this point, ';', ';;' or other token.这是一个类似的例子,但更难。
>sprintf "%a";;
error FS0030: Value restriction. The value 'it' has been inferred to have generic type
val it : ((unit -> '_a -> string) -> '_a -> string)
Either make the arguments to 'it' explicit or, if you do not intend for it to be generic, add a type annotation.发布于 2012-07-05 16:11:21
你只需要把你的表达式放在括号里:
open System;;
(sprintf "%A" : DateTime -> string);;
val it : (DateTime -> string) = <fun:it@2>这样,您就可以在没有绑定的情况下指定类型注释。
发布于 2012-07-05 16:05:45
实际发生的情况是,fsi将您输入的最后一个内容绑定到一个名为it的变量。它有效地做到了
let it = sprintf "%a";;类型注释需要放在=的左侧,您无法访问它。问题是您需要一个具体的类型来赋予任何变量(在本例中为it)。一种解决方法可能是
(fun t:DateTime -> sprintf "%a" t)https://stackoverflow.com/questions/11339943
复制相似问题