Loop, string chars. While F# programs can use many advanced features, often they need to perform simpler tasks like looping over a string. This can be done in many ways in F#.
Version 3 We can iterate over indexes, and then access each char by index, with a for-to loop.
Version 4 It is possible to access the characters from the string with the Chars accessor.
Version 5 For a reverse loop with indexes, we can use for downto—this is a decrementing index loop.
let value = "abc"// Version 1: use for-in.
for c in value do
printfn $"For-in: {c}"// Version 2: use for-in with Seq.rev for reverse loop.
for c in Seq.rev value do
printfn $"Seq.rev: {c}"// Version 3: use for-to loop.
for i = 0 to value.Length - 1 do
let c = value[i]
printfn $"For-to []: {c}"// Version 4: Use for-to loop with Chars.
for i = 0 to value.Length - 1 do
let c = value.Chars(i)
printfn $"For-to Chars: {c}"// Version 5: use for-downto loop for reverse loop.
for i = value.Length - 1 downto 0 do
let c = value[i]
printfn $"For-downto: {c}"For-in: a
For-in: b
For-in: c
Seq.rev: c
Seq.rev: b
Seq.rev: a
For-to []: a
For-to []: b
For-to []: c
For-to Chars: a
For-to Chars: b
For-to Chars: c
For-downto: c
For-downto: b
For-downto: a
Summary. Looping is often done in F#, and looping over strings is a common requirement as well. With for-in and for-to, we have a variety of powerful loops to choose from.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.