Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
F# 是否可以创建自定义Printf.textWritePerformat?_F# - Fatal编程技术网

F# 是否可以创建自定义Printf.textWritePerformat?

F# 是否可以创建自定义Printf.textWritePerformat?,f#,F#,我想在F中创建一个自定义类型,类似于Printf.textWritePerformat添加my%。参数。 可能吗 另外,我只找到了 编辑: 我想添加带有生成静态类型的新限定符。或者使用生成静态类型创建我的格式字符串。我不想使用标准Printf.textWritePerformat或与之结合使用。不,您不能创建任意格式的文本。您最接近的方法是使用相当模糊的%a,它是类型安全的,可能正是您所要求的: open System open System.IO type MyRecord = {

我想在F中创建一个自定义类型,类似于Printf.textWritePerformat添加my%。参数。 可能吗

另外,我只找到了

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

不,您不能创建任意格式的文本。您最接近的方法是使用相当模糊的%a,它是类型安全的,可能正是您所要求的:

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
丑陋的是,根据我使用的sprintf和printfn代码中使用的格式函数,必须为自定义类型提供不同的格式函数

好消息是:

let printMyRecord = printfn "%a" formatIntoWriter

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

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