gpt4 book ai didi

sprintf 和格式的 F# 错误

转载 作者:行者123 更新时间:2023-12-05 01:28:15 24 4
gpt4 key购买 nike

我为字符串使用资源文件,然后还使用那些带有占位符和需要格式化字符串的资源文件。

我的项目中有(大约)以下代码:

let create s = sprintf (Printf.StringFormat<_>(s)) 

let formatstring = "%s:%d" // this is actually then gotten from the resource strings

let createsomespecificstring s d = create formatstring s d

let resultstring = createsomespecificstring "123" 123

此代码在我使用 f#3.0 时有效。交换它以使用 3.1 编译它,它编译但给出运行时错误:

Unable to cast object of type 'Final2@235[Microsoft.FSharp.Core.Unit,System.String,System.String,System.String,System.String]' to type 'Microsoft.FSharp.Core.FSharpFunc2[Microsoft.FSharp.Core.FSharpFunc2[Microsoft.FSharp.Core.Unit,Microsoft.FSharp.Core.PrintfImpl+PrintfEnv3[Microsoft.FSharp.Core.Unit,System.String,System.String]],Microsoft.FSharp.Core.FSharpFunc2[System.String,Microsoft.FSharp.Core.FSharpFunc`2[System.String,System.Object]]]'.

如果我在 repl 中运行上面的代码,它根本不起作用:

stdin(28,5): error FS0030: Value restriction. The value 'resultstring' has been inferred to have generic type val resultstring : '_a
Either define 'resultstring' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation.

上面的代码在某种程度上再次破坏了强类型的目的,但是当有资源字符串时它有点好。

我是不是做错了什么(除了上面提到的)?

关于如何做得更好甚至让它发挥作用(尤其是在 3.1 中)有什么想法吗?

编辑:在第一个答案(在特定情况下有效)之后,格式化选项/参数的数量是“随机”长度:

let formatstring = "%s:%d:%d"
let createsomespecificstring s d d' = create formatstring s d d'
let resultstring = createsomespecificstring "123" 123 345

然后又不行了。

最佳答案

@kvp 提示的类型注释是“正确”答案。

let createsomespecificstring s d d' : string = create formatstring s d d'

在 fsi 和 f# 3.1 中,当根据我完成的测试编译时,它就是这样做的。

关于sprintf 和格式的 F# 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27433692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com