C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
open System
// 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
Output
100
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.ofArray candies
|> Seq.where (fun x -> x.StartsWith("c"))
|> Seq.toArray
printfn "%A" firstLetterC
Output
[|"chocolate"; "cookie"|]
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
Output
20
F# program that converts bool to 1 or 0
let code = true
// Convert bool to 1 or 0.
let number = if code then 1
else 0
printfn "%A" code
printfn "%A" number
Output
true
1