F# For Dummys – Day 6

f#-for-dummys-–-day-6

Today we learn how to format the output of println, and a new type char
what is formatting?
formatting is converting values into strings according to a specified format
we introduce 2 ways to format
String interpolation: one way to combine variables and text is to use something called interpolation
actually we used it yesterday

let name = "Lucy"
let age = 14
printfn $"my name is {name}, I'm {age} years old"

$ tell the compiler: please use the variable we defined before in this string
{} indicate what exactly the variables we need, here in this example is {name} and {age}
so it will replace the value of variables at the location of brace
like type of age is int, it’s converted to string ’14’ in the final output, we didn’t transfer it explicitly

Specifiers: You can also use format specifiers as part of what you’re trying to print. Using specifiers is the most commonly used way to format in F#
Let’s use specifier to format in our example:

let name = "Lucy"
let age = 14
printfn "my name is %s, I'm %i years old" name age

you can see the output is the same
%s is for name, it’s for string type
%i is for age, it’s for int type
we introduce 4 of them today:

Image description

%b for bool

let is_this_apple = true
let is_this_orange = false

printfn "Is this an apple? %b" is_this_apple
printfn "Is this an orange? %b" is_this_orange

%c for char
we have learned string type to describe a text, it represents a sequence of characters
while char represents a single character, like ‘a’, ‘b’, ‘c’, ‘d’ or ‘!’, ‘@’, ‘#’, ‘$’
string and char are different types, not just the length, you can not concat them like this:

let str = "Hello"
let ch = '!'
let result = str + ch

printfn "%s" result  // Output: Hello!

will get error: The type ‘char’ does not match the type ‘string’

Image description

we can transfer a char to string like this, then can concat them properly

let str = "Hello"
let ch = '!'
let result = str + (string)ch

printfn "%s" result  // Output: Hello!

the full specifiers for other types are here

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
python-flipping-calendars.

Python. Flipping Calendars.

Next Post
the-rise-of-ai-in-web-design:-5-game-changing-ways-ai-is-revolutionizing-the-industry

The Rise of AI in Web Design: 5 Game-Changing Ways AI is Revolutionizing the Industry

Related Posts