【问题标题】:Is it possible to create a custom Printf.TextWriterFormat?是否可以创建自定义 Printf.TextWriterFormat?
【发布时间】:2017-03-11 15:38:18
【问题描述】:

我想在 F# 中创建一个自定义类型,类比 Printf.TextWriterFormat(添加我的 %. 参数)。 有可能吗?

附:我只找到how to create custom Type provider

编辑: 我想添加具有生成静态类型的新限定符。或者使用生成静态类型创建我的格式字符串。我不想使用标准的Printf.TextWriterFormat 或与它结合使用。

【问题讨论】:

  • 如果您想在函数中使用 printf 样式的字符串格式,然后对生成的字符串应用一些自定义逻辑,请参阅链接问题。
  • @scrwtp 我想添加具有生成静态类型的新限定符。或者使用生成静态类型创建我的格式字符串。
  • @FoggyFinder 例如,我想写:'printfn "%w" MyRequest'(或 'MyCustomPrintFunction "%w" MyRequest')。编译器检查 MyRequest 是否具有 WebRequest 类型。
  • 您能解释一下为什么需要这个吗?

标签: f#


【解决方案1】:

不,您不能创建任意格式的文字。你能得到的最接近的是使用相当模糊的"%a"format specificier,它是类型安全的,可能正是你所要求的:

open System
open System.IO


type MyRecord = {
    Name  : String
    Value : Int32
}


let myRecord = {
    Name  = "Hello World"
    Value = 42
}


let formatAsString () { Name = name; Value = value } =
    sprintf "RECORD NAME \"%s\" AND VALUE \"%d\"!" name value


let formatIntoWriter (writer : TextWriter) =
    formatAsString () >> writer.Write


// Functions from the Core.Printf module that return strings
// require a format function that returns a string.
let formattedAsString = sprintf "%a" formatAsString myRecord

// Functions from the Core.Printf module that return Unit
// require a format function that accepts a TextWriter.
printfn "%a" formatIntoWriter myRecord

丑陋的地方在于,根据您使用的格式函数(在我使用sprintfprintfn 的代码中),您必须为您的自定义类型提供不同的格式函数。

好消息是:

let printMyRecord = printfn "%a" formatIntoWriter

现在有MyRecord -> Unit 类型,因此您只能将MyRecord 的实例传递给它。

【讨论】:

    猜你喜欢
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多