How to return a formatted string from a function?

I am learning F #, so forgive me if it is very simple. I have a function that should return a 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 the .NET string.Format , but wondered if there is an F # way to do this?

+5
source share
2 answers

You have an extra comma in your sprintf call, try the following:

 let getDoubled x = sprintf "%d doubled is %d" x (x * 2) 

A comma means that you are creating a tuple, and this is what you have in the second fragment - the function tuple (your partially applied sprintf , which expects the second argument) and int (the result is x*2 ).

+8
source

I donโ€™t think you need commas.

It:

 let getDoubled x = sprintf "%d doubled is %d" x, x * 2 

Must be:

 let getDoubled x = sprintf "%d doubled is %d" x (x * 2) 
+3
source

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


All Articles