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

查看:81
本文介绍了如何使用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之类的函数作为参数传递给其他函数,然后将它们与多个不同的参数一起使用.问题在于printf是类型Printf.TextWriterFormat<'a> -> '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天全站免登陆