Console printing and array processing

I am handling a large number of objects allocated in an array. This processing takes a long time and I would like to be able to control if the fx were in the processing step.

My goal is to be able to print to the console of some kind Processing thing number *x*

while continuing to work. For example, while

let x = [|1..10..100000|]

x 
|> Array.mapi (fun i n -> (i, n))
|> Array.map (fun (i, n) -> printfn "Processing n %i" i, (n * 2)))
|> Array.map snd

      

I am getting output for each line. I would like every 10 or 100 or 1000 to print an expression, not every line. So I tried

x 
|> Array.mapi (fun i n -> (i, n))
|> Array.map (fun (i, n) -> (if (i % 100 = 0) then printfn "Processing n %i" i, (n * 2)))
|> Array.map snd

      

but this provides an error over the bit printfn...

with

The 'if' expression is missing an else branch. The 'then' branch has type
''a * 'b'. Because 'if' is an expression, and not a statement, add an 'else'
branch which returns a value of the same type.

      

I want the branch else...

to do nothing, print nothing to the console, just be ignored.

Interestingly, while writing this question and trying in, FSI

I've tried this:

x 
|> Array.mapi (fun i n -> (i, n))
|> Array.map (fun (i, n) -> match (i % 100 = 0) with 
                            | true -> printfn "Processing n %i" i, (n * 2)
                            | false -> (), n * 2)
|> Array.map snd

      

which seems to work. Is this the best way to provide console text?

+3


source to share


1 answer


It sounds like you want:

let x' = x |> Array.mapi (fun i n ->
        if i % 100 = 0 then
            printfn "Processing n %i" i
        n)

      

Both branches of the expression if

must be of the same type and



if (i % 100 = 0) then printfn "Processing n %i" i, (n * 2)

      

returns the type value (unit, int)

for the true case. The missing case is else

implicitly of type ()

, so the types are not the same. You can simply print the value, ignore the result, and then return the current value.

+3


source







All Articles