Strings and Runes in F#

open System

// A string in F# is a sequence of Unicode characters.
// F# strings are immutable, similar to Go strings.

// Define a string constant with Thai characters
let s = "สวัสดี"

// Print the length of the string (in characters, not bytes)
printfn "Len: %d" (String.length s)

// In F#, we can iterate over characters in a string directly
printfn "Character values:"
for c in s do
    printf "%x " (int c)
printfn ""

// Count the number of characters (equivalent to runes in Go)
printfn "Character count: %d" (String.length s)

// Iterate over characters with their indices
s |> String.iteri (fun i c ->
    printfn "%c starts at %d" c i
)

// Define a function to examine characters
let examineChar (c: char) =
    match c with
    | 't' -> printfn "found tee"
    | 'ส' -> printfn "found so sua"
    | _ -> ()

printfn "\nUsing String.iteri"
s |> String.iteri (fun i c ->
    printfn "%c starts at %d" c i
    examineChar c
)

This F# code demonstrates working with strings and characters, which is analogous to working with strings and runes in Go. Here’s a breakdown of the code:

  1. We define a string s containing Thai characters.

  2. We use String.length to get the length of the string in characters (equivalent to utf8.RuneCountInString in Go).

  3. We iterate over the string to print the hexadecimal value of each character.

  4. We demonstrate iterating over the string with indices using String.iteri.

  5. We define an examineChar function that checks for specific characters, similar to the examineRune function in the Go example.

  6. Finally, we use String.iteri again to iterate over the string, printing each character’s position and examining it.

Note that F# strings are sequences of Unicode characters by default, so we don’t need to do explicit UTF-8 decoding as in the Go example. The char type in F# represents a Unicode character, similar to a rune in Go.

To run this F# program, you would typically save it as a .fs file and use the F# compiler or an F# interactive environment:

$ fsharpc strings_and_chars.fs
$ mono strings_and_chars.exe

Or in F# Interactive:

$ fsharpi strings_and_chars.fs

This will execute the program and show the output, demonstrating how F# handles strings and characters in a way similar to Go’s handling of strings and runes.