Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does F#'s printfn work with literal strings, but not values of type string?

Tags:

.net

f#

In the following F# code; I would expect that the printfn is being called three times; each with a string. However, the bottom line does not compile (The type 'string' is not compatible with the type 'Printf.TextWriterFormat<'a>').

What is it about the first two lines that means this can work? Aren't they just strings too?

open System

printfn ("\r\n") // Works
printfn ("DANNY") // Works
printfn (DateTime.Now.ToLongTimeString()) // Doesn't compile
like image 479
Danny Tuppeny Avatar asked Aug 31 '13 19:08

Danny Tuppeny


People also ask

What does f x )= y mean?

Simply put, the Y=f(x) equation calculates the dependent output of a process given different inputs.

What is f in math called?

Function (mathematics) - Wikipedia.

What does f say about f?

What Does f ' Say About f ? The first derivative of a function is an expression which tells us the slope of a tangent line to the curve at any instant. Because of this definition, the first derivative of a function tells us much about the function. If is positive, then must be increasing.

Is f x the same as Y?

Functions are different in a key way from equations: a function is an output. An equation is a relationship between variables. Yes, y=x+3 and f(x)= x+3 yield the same results, which is why we teachers always tell you to remember that 'y and f(x) are the same thing'.


1 Answers

The F# compiler statically analyses the format strings you pass to printfn to check that the arguments you pass are valid for the format specifiers you use. For example, the following does not compile:

printfn "%d" "some value"

since string is not compatible with the %d format specifier. The compiler converts valid format strings into a TextWriterFormat<T>.

It can't do this with arbitrary strings, and since it does not do the conversion, you get the type error above.

You can do the conversion yourself however using Printf.TextWriterFormat. For example, for a format string requiring a string and an int you can use:

let f = Printf.TextWriterFormat<string -> int -> unit>("The length of '%s' is: %d")
printfn f "something" 9

Since your string has no format placeholders, you can do:

let f = Printf.TextWriterFormat<unit>(DateTime.Now.ToLongTimeString())
printfn f
like image 112
Lee Avatar answered Sep 20 '22 18:09

Lee