是否可以部分应用诸如 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/