Is there an easy way to print each element of an array?
Using a String.concat
delimited string to concatenate is probably the best option in this case (because you don't want the delimiter at the end).
However, if you just want to print all items, you can also use Array.iter
:
let nums= [|15..20|]
Array.iter (fun x -> printfn "%O" x) nums // Using function call
nums |> Array.iter (fun x -> printfn "%O" x) // Using the pipe
Adding delimiters in this case is more difficult, but possible with iteri
:
nums |> Array.iteri (fun i x ->
if i <> 0 then printf ", "
printf "%O" x)
source to share
If the array of elements is large and you do not want to generate a large string, another option is to generate an alternating sequence and skip the first element. The following code works assuming the array has at least one element.
One of the advantages of this approach is that it cleanly separates the interleaving and printing action. It also eliminates the need to check for the first item on each iteration.
let items = [| 15 .. 20|]
let strInterleaved delimiter items =
items
|> Seq.collect (fun item -> seq { yield delimiter; yield item})
|> Seq.skip(1)
items
|> Seq.map string
|> strInterleaved ","
|> Seq.iter (printf "%s")
source to share