2017-04-21 74 views
3

我正在處理數組中的大量對象。這個處理需要很長時間,我希望能夠監控fx是否處於處理階段。打印到控制檯並處理數組

我的目標是能夠在繼續操作的同時向控制檯打印某種Processing thing number *x*。例如,與此

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 

我得到每行的輸出。我想有什麼是每10或100或1000打印一個聲明,而不是每一行。所以,我已經試過

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 

但這提供了一個錯誤在printfn...位與

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. 

我基本上希望else...分支什麼都不做,什麼都不打印到控制檯,就可以忽略。

有趣的是,在寫這個問題,並在FSI嘗試新事物,我想這一點:

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 

這似乎工作。這是提供控制檯文本的最佳方式嗎?

回答

3

它看起來像你想:

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

if表達的兩個分支必須具有相同的類型和

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

返回真實的情況下,(unit, int)類型的值。缺少的else案例隱含地具有類型(),因此類型不匹配。您只需打印該值,忽略結果並返回當前值。

+0

完美。這比我上面的'match'陳述少得多!謝謝。 – Steven