Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return formatted string from a function?

Tags:

.net

f#

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?

like image 876
Saravana Avatar asked Dec 07 '14 12:12

Saravana


People also ask

Can I return a string from a function?

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.

What is return by format () method?

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.

What's a formatted string?

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.


1 Answers

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).

like image 155
scrwtp Avatar answered Oct 01 '22 14:10

scrwtp