如何创建带有 printf 样式日志参数的 F# 函数? [英] How do I create an F# function with a printf style logging argument?

查看:24
本文介绍了如何创建带有 printf 样式日志参数的 F# 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个框架来处理文件和数据.我正在努力解决的一个领域是如何为框架提供日志记录功能,允许框架在不了解正在使用的日志记录的情况下报告消息.

I'm trying to create a framework to do some processing of files and data. The one area I'm struggling with is how to provide a logging function to the framework, allowing the framework to report messages without having any knowledge of the logging in use.

let testLogger (source:seq<'a>) logger =
    logger "Testing..."
    let length = source |> Seq.length
    logger "Got a length of %d" length


let logger format = Printf.kprintf (printfn "%A: %s" System.DateTime.Now) format
testLogger [1; 2; 3] logger

理想情况下,我希望这段代码能够工作,但我不知道如何传入记录器函数.

Ideally I want this code to work, but I can't work out how to pass the logger function in.

推荐答案

遗憾的是,您不能将像 printf 这样的函数作为参数传递给其他函数,然后将它们与多个不同的参数一起使用em>.问题在于 printfPrintf.TextWriterFormat<'a> 类型的通用函数.->'一个.替换类型参数 'a 的实际类型是一些函数类型,每次使用 printf 时都不同(例如 'a == string -> unit 用于 "%s" 等).

Unfortunately, you cannot pass functions like printf as parameters to other functions and then use them with multiple different arguments. The problem is that printf is a generic function of type Printf.TextWriterFormat<'a> -> 'a. The actual type substituted for the type parameter 'a is some function type that is different each time you use printf (e.g. 'a == string -> unit for "%s" etc).

在 F# 中,您不能拥有本身是泛型函数的函数的参数.泛型函数必须是某个全局函数,但您可以通过实际对字符串执行某些操作的函数对其进行参数化.这基本上是 kprintf 所做的,但您可以更好地命名您的函数:

In F#, you cannot have parameter of a function that is itself a generic function. The generic function will have to be some global function, but you can parameterize it by the function that actually does something with the string. This is essentially what kprintf does, but you can name your function better:

let logPrintf logger format = 
    Printf.kprintf logger format

由记录器参数化的函数示例如下:

An example of function parameterized by the logger would be:

let testLogger (source:seq<'a>) logger =
    logPrintf logger "Testing..."
    let length = source |> Seq.length
    logPrintf logger "Got a length of %d" length


let logger = printfn "%A: %s" System.DateTime.Now
testLogger [1; 2; 3] logger

这篇关于如何创建带有 printf 样式日志参数的 F# 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆