I am learning F# so pardon me if this is very basic. I have a function that is supposed to return formatted string:
> let getDoubled x = sprintf "%d doubled is %d" x, x * 2;;
But when I execute this function it returns the following:
> getDoubled 2;;
val it : (int -> string) * int = (<fun:getDoubled@24-1>, 4)
I know I can use .NET's string.Format
but was wondering if there was any F# way of doing it?
Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid. Note the use of const , because from the function I'm returning a string literal, a string defined in double quotes, which is a constant.
format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.
String formatting uses a process of string interpolation (variable substitution) to evaluate a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.
You have an extra comma in your sprintf call, try this:
let getDoubled x = sprintf "%d doubled is %d" x (x * 2)
The comma means you are constructing a tuple, and this is what you have in your second snippet - a tuple of a function (your partially applied sprintf
that's waiting for the second argument) and an int (the result of x*2
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With