generics - 保持部分应用的函数通用

标签 generics f# value-restriction

是否可以部分应用诸如 bprintf 之类的功能?并防止它因最初使用而受到限制?

我想做以下事情:

let builder = new System.Text.StringBuilder()
let append = Printf.bprintf builder
append "%i" 10
append "%s" string_value

最佳答案

导致这种情况的 F# 方面称为值限制。你可以看到,如果你只输入两个 let对 F# Interactive 的声明(以便编译器不会从第一次使用中推断出类型):

> let builder = new System.Text.StringBuilder() 
  let append = Printf.bprintf builder ;;

error FS0030: Value restriction. The value 'append' has been inferred to have generic type val append : ('_a -> '_b) when '_a :> Printf.BuilderFormat<'_b> Either make the arguments to 'append' explicit or, if you do not intend for it to be generic, add a type annotation.



有一个excellent article by Dmitry Lomov来自 F# 团队的详细解释。正如文章所建议的,一种解决方案是添加显式类型参数声明:
let builder = new System.Text.StringBuilder() 
let append<'T> : Printf.BuilderFormat<'T> -> 'T = Printf.bprintf builder 
append "%i" 10 
append "%s" "Hello"

这将工作得很好。

关于generics - 保持部分应用的函数通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4047308/

相关文章:

c# - 如何从 List<T> 获取 IEnumerable<T>?

Java 类使用未经检查或不安全的操作

f# - 为什么我需要一个类型注解?

F# 编译器错误 FS0030,值限制问题

c# - 无法将类型 'System.Collections.IList' 隐式转换为 'System.Collections.Generic.List

java - List<Dog> 是 List<Animal> 的子类吗?为什么 Java 泛型不是隐式多态的?

f# - 如何使用 FSharp.Data 的 http 模块下载大文件?

f# - FSharp.核心 : Could not load file or assembly

python - 将定义集中的值设置为 pandas 数据框中列的给定值(例如 NaN)

list - 当参数为空列表时,如何避免值限制错误?