Convert. A string has a value like "100." With a parsing method, we can convert that to an Int. This is a more efficient representation of the data.
For simple conversions, a cast like downcast or upcast is sufficient. For parsing a string, we use Int32.TryParse. For arrays, Seq.asArray and toArray are helpful.
Convert string to int. To convert a number in a string into an int, we use the Int32.TryParse. Other types like Int64 also have equivalent parsing methods.
Start We must declare a "parsed value" storage location. We decorate this value (result) with the mutable keyword so it can be changed.
Info The first argument is the string. The second one is the storage variable for the parsed value—we pass it as a reference.
Return When TryParse returns true, we enter the if-block. In this case the parse was successful and the result was assigned.
// This string contains an Int32.
let test = "100"
// Stores the parsed value from TryParse.
let mutable result = 0
// If TryParse succeeds, value is stored in result.
if Int32.TryParse(test, &result) then
// Print the parsed value.
printfn "%A" result100
Seq.ofArray, toArray. A Seq is powerful: we can use many methods on it, like "where" or "map." With Seq.ofArray we treat an array as a sequence.
Here We use the Seq.where method on an array (which is being treated as a sequence).
Result We remove elements that do not start with "C" and convert the result back into a string array with Seq.toArray.
// This is a string array.
let candies = [|"chocolate"; "sugar"; "cookie"|]
// Use Seq.ofArray to convert to a seq.// ... Use Seq.toArray to convert seq to a string array.
let firstLetterC =
|> Seq.where (fun x -> x.StartsWith("c"))
printfn "%A" firstLetterC[|"chocolate"; "cookie"|]
Option to int. In F# many methods return an option. We can convert the option to a value by testing it with IsSome. If an inner value exists, we then access it with Value.
let numbers = [10; 20; 30]
// The tryFind method returns an option containing an int.
let result = List.tryFind (fun x -> x >= 15) numbers
// See if the option has a value.
if result.IsSome then
// Convert the option into an Int.
let number = result.Value
printfn "%d" number20
Bool to int. Sometimes we have a bool and want to convert it to an int—usually 1 for true and 0 for false. An inline if-expression can be used to do this.