F# Convert String, Int, Array and SeqUse Int32.TryParse with a ref parameter to safely parse a string. Convert a string to an Int.
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.
Mutable: We must declare a "parsed value" storage location. We decorate this value (result) with the mutable keyword so it can be changed.
Int32.TryParse: 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.
F# program that uses Int32.TryParse
// 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" result
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.Seq
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.
F# program that uses Seq.ofArray, 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
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.Option
F# program that converts option
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" number
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.if, elif
F# program that converts bool to 1 or 0
let code = true
// Convert bool to 1 or 0.
let number = if code then 1
printfn "%A" code
printfn "%A" number
With conversions, we change types of our data so that is it more useful. Ints are more effective when dealing with numeric data than strings containing digits.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.