In F #, how do you execute ParamArray functions (like sprintf)?

In F #, how do you execute a function that takes a variable number of parameters?

I have code like this ... (the log function is just an example, the exact execution doesn't matter)

let log (msg : string) = printfn "%s" msg log "Sample" 

It is called throughout the code using sprintf formatted strings, for example

 log (sprintf "Test %s took %d seconds" "foo" 2.345) 

I want to archive the sprintf functionality in a log function so that it looks like ...

 logger "Test %s took %d seconds" "foo" 2.345 

I tried something like

 let logger fmt ([<ParamArray>] args) = log (sprintf fmt args) 

but I can't figure out how to pass the ParamArray argument through a sprintf call.

How is this done in F #?

+6
source share
2 answers
 let log (s : string) = () let logger fmt = Printf.kprintf log fmt logger "%d %s" 10 "123" logger "%d %s %b" 10 "123" true 
+7
source

The behavior of printf functions in F # is somewhat special. They take a format string that contains the expected arguments. You can use Printf.kprintf as shown by desco to define your own function that accepts a format string, but you cannot change the handling of format strings.

If you want to do something like C # params (where the number of arguments is a variable, but does not depend on the format string), you can use the ParamArray attribute directly for the member:

 open System type Foo = static member Bar([<ParamArray>] arr:obj[]) = arr |> Seq.mapi (fun iv -> printfn "[%d]: %A" iv) 

Then you can call Foo.Bar with any number of arguments without a format string:

 Foo.Bar("hello", 1, 3.14) 

This is less elegant for formatting strings, but may be useful in other situations. Unfortunately, it will only work with members (and not with functions defined with let )

+6
source

Source: https://habr.com/ru/post/918699/


All Articles