string
charsWhile 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#.
For the least complex looping requirements, a for-in
loop is best. But if we need the index of each character, a for-to
loop is a better choice.
For clarity, we use a string
with the value "abc". Then we iterate over its characters, in forward and reverse order, in different ways.
char
.for-in
, we can implement a reverse loop by passing the string
to Seq.rev
first.char
by index, with a for-to
loop.string
with the Chars accessor.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
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.