skip to Main Content

I have a function that takes a string and sends it to a terminal:

Print: string -> unit

it is passed to several modules that do this, to simplify the syntax

// printing
let print = settings.Print

and then it’s used like that:

print "hello"
print (sprintf "the time is %A" DateTime.UtcNow)

my question is: Can I make two functions, with the same name but two signatures, so I could use it to either print a string, or a sprintf, then print the string.
for example:

print "hello"
print "the time is %A" DateTime.UtcNow

Is this possible? the goal is to simplify the syntax as a lot of code is peppered with info being sent to the terminal (which is currently a Telegram channel)

2

Answers


  1. You can use the same signature as sprintf:

    let print (format : Printf.StringFormat<'T>) =
        sprintf format
        |> dosomethingElse
    

    and you can use it as you want:

    print "hello"
    print "the time is %A" DateTime.UtcNow
    
    Login or Signup to reply.
  2. You can use kprintf for this:

    let myPrint s = printfn "My print: %s !" s
    
    let print x = Printf.kprintf myPrint x
        
    print "%d" 1
    print "aaaa"
    print "%s %s" "b" "c"
    

    There are some examples here and here.

    I couldn’t find kprintf documentation, so I’m not sure that this usage is correct, but it produces the correct result for me. Another possible candidate is ksprintf, which also produces the same result.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search