Is there an easy way to print each element of an array?

let x=[|15..20|]
let y=Array.map f x
printf "%O" y

      

Well, I got the type information.

Is there a way to print each "y" element with a "," separator without having to use a for loop?

+3


source to share


4 answers


Use String.Join

in namespace System

or F # 'native':



let x = [| 15 .. 20 |]

printfn "%s" (System.String.Join(",", x))

x |> Seq.map string |> String.concat "," |> printfn "%s"

      

+7


source


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) 

      

+2


source


This will not print the entire array if it is large; I think it only prints the first 100 items. However, I suspect this is what you need:

printfn "%A" y

      

+1


source


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")

      

0


source







All Articles