Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

continuations - syntax issue around kprintf in F#

I have a project using NLog and there is a wrapper around the logger, in order to turn logging off in some areas:

member this.SetQuiet q = quiet <- q

member this.Trace format = Printf.kprintf (fun s -> if not quiet then logger.Trace(s)) format
member this.Debug format = Printf.kprintf (fun s -> if not quiet then logger.Debug(s)) format
member this.Info  format = Printf.kprintf (fun s -> if not quiet then logger.Info(s))  format
member this.Warn  format = Printf.kprintf (fun s -> if not quiet then logger.Warn(s))  format
member this.Error format = Printf.kprintf (fun s -> if not quiet then logger.Error(s)) format
member this.Fatal format = Printf.kprintf (fun s -> if not quiet then logger.Fatal(s)) format

this works quite well, but I have an issue:

logger.Info "hello"
logger.Info <| "hello"

will work properly, whereas:

"hello" |> logger.Info

will not compile with this error:

typecheck error The type 'string' is not compatible with the type 'Printf.StringFormat<'a,string>'

can someone explain me why this fails? the order kprintf-continuation-format should still be respected here, no?

Is there a workaround for this? the reason is that I'm trying to do a 'tee' to log messages in a non verbose way (the tee just applies a function and then returns the original parameter):

"my messsage"
|> tee logger.Info
|> Result.Ok
question from:https://stackoverflow.com/questions/66064895/syntax-issue-around-kprintf-in-f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That happens because printf and similar methods uses formatting. It allows type-safe usage of these method. For example printfn "%d" enforces integer as parameter

printfn "%d" 3
printfn "%d" 3.14 // error

printfn "%s %f" enforces string and float.

printfn "%s %f" "Hello" 3.14
printfn "%s %f" '3' 14 // error

This means that you should change methods this way (added "%s")

member this.Trace format = Printf.kprintf (fun s -> if not quiet then logger.Trace(s)) "%s" format

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...