保持部分应用的函数通用

发布于 2024-09-29 10:46:43 字数 209 浏览 15 评论 0原文

是否可以部分应用 bprintf 等函数并防止其根据其初始使用而受到限制?

我想做以下事情:

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

Is it possible to partially apply a function such as bprintf and prevent it from being restricted based on its initial use?

I'd like to do the following:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

櫻之舞 2024-10-06 10:46:43

F# 中导致此问题的方面称为“值限制”。您可以看到,如果您仅向 F# Interactive 输入两个 let 声明(以便编译器不会从第一次使用时推断类型):

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

错误 FS0030:值限制。值“append”已被推断为
泛型类型 val 附加 : ('_a -> '_b) 当 '_a :> Printf.BuilderFormat<'_b>;
要么明确“append”的参数,要么,如果您不打算这样做
要使其通用,请添加类型注释。

有一个 F# 团队的 Dmitry Lomov 撰写的优秀文章,详细解释了这一点。正如文章所建议的,一种解决方案是添加显式类型参数声明:

let builder = new System.Text.StringBuilder() 
let append<'T> : Printf.BuilderFormat<'T> -> 'T = Printf.bprintf builder 
append "%i" 10 
append "%s" "Hello"

这会很好地工作。

The aspect of F# that's causing this is called value restriction. You can see that if you enter just the two let declarations to F# Interactive (so that the compiler doesn't infer the type from the first use):

> 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.

There is an excellent article by Dmitry Lomov from the F# team which explains it in detail. As the article suggests, one solution is to add explicit type parameter declaration:

let builder = new System.Text.StringBuilder() 
let append<'T> : Printf.BuilderFormat<'T> -> 'T = Printf.bprintf builder 
append "%i" 10 
append "%s" "Hello"

This will work just fine.

落在眉间の轻吻 2024-10-06 10:46:43

您可以添加明确的格式参数

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

you can add explicit format argument

let builder = new System.Text.StringBuilder()
let append format = Printf.bprintf builder format
append "%i" 10
append "%s" "1"
季末如歌 2024-10-06 10:46:43

您遇到了 F# 值限制。

以下是一些解决方法的很好解释:了解 F# 值限制错误

这是一个相当详细的内容 -深度文章解释其背后的原因: 链接

You're encountering the F# value restriction.

Here's a good explanation of some workarounds: Understanding F# Value Restriction Errors

Here's a fairly in-depth article explaining the reasons behind it: Link

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文