2017-04-21 72 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