Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to print each element of an array?

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

Well, I got a type information.

Is there any way to print each element of "y" with delimiter of ",", while not having to use a for loop?

like image 663
vik santata Avatar asked Dec 11 '25 21:12

vik santata


2 Answers

Either use String.Join in the System namespace or F# 'native':

let x = [| 15 .. 20 |]

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

x |> Seq.map string |> String.concat "," |> printfn "%s"
like image 168
CaringDev Avatar answered Dec 14 '25 20:12

CaringDev


Using String.concat to concatenate the string with a separator is probably the best option in this case (because you do not want to have the separator at the end).

However, if you just wanted to print all elements, 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 the separators in this case is harder, but possible using iteri:

nums |> Array.iteri (fun i x ->
  if i <> 0 then printf ", "
  printf "%O" x) 
like image 23
Tomas Petricek Avatar answered Dec 14 '25 19:12

Tomas Petricek