首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在哪里给curried函数添加类型注解?

在哪里给curried函数添加类型注解?
EN

Stack Overflow用户
提问于 2012-07-05 15:47:23
回答 2查看 782关注 0票数 3

在中,我可以找到F#的类型。

代码语言:javascript
复制
>sprintf;;
val it : (Printf.StringFormat<'a> -> 'a) = <fun:clo@163>

如果curried函数不是泛型的,我可以用第一个参数找到curried的sprintf类型。

代码语言:javascript
复制
> sprintf "%g";;
val it : (float -> string) = <fun:it@134-16>

但是如果它是泛型的,那么我就会得到值限制错误。

代码语言:javascript
复制
> 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。

代码语言:javascript
复制
>let f : (DateTime -> string) = sprintf "%A";;
val f : (DateTime -> string)

如何在没有绑定的情况下添加类型批注?我试过以下几种方法……

代码语言:javascript
复制
>sprintf "%A" : (DateTime -> string);;
error FS0010: Unexpected symbol ':' in interaction. Expected incomplete structured construct at or before this point, ';', ';;' or other token.

这是一个类似的例子,但更难。

代码语言:javascript
复制
>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.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-05 16:11:21

你只需要把你的表达式放在括号里:

代码语言:javascript
复制
open System;;
(sprintf "%A" : DateTime -> string);;

val it : (DateTime -> string) = <fun:it@2>

这样,您就可以在没有绑定的情况下指定类型注释。

票数 3
EN

Stack Overflow用户

发布于 2012-07-05 16:05:45

实际发生的情况是,fsi将您输入的最后一个内容绑定到一个名为it的变量。它有效地做到了

代码语言:javascript
复制
let it = sprintf "%a";;

类型注释需要放在=的左侧,您无法访问它。问题是您需要一个具体的类型来赋予任何变量(在本例中为it)。一种解决方法可能是

代码语言:javascript
复制
(fun t:DateTime -> sprintf "%a" t)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11339943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档