F# 打印到控制台并处理阵列

F# 打印到控制台并处理阵列,f#,console.writeline,F#,Console.writeline,我正在处理一个数组中的大量对象。这个处理需要很长时间,我希望能够监控外汇是否在处理步骤中 我的目标是能够在继续操作的同时向控制台打印某种处理对象编号*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 我

我正在处理一个数组中的大量对象。这个处理需要很长时间,我希望能够监控外汇是否在处理步骤中

我的目标是能够在继续操作的同时向控制台打印某种
处理对象编号*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

这似乎有效。这是提供控制台文本的最佳方式吗?

看起来您需要:

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)

对于真实情况,返回类型为
(单位,int)
的值。缺少的
else
案例隐式具有类型
()
,因此类型不匹配。您可以只打印值,忽略结果,然后返回当前值。

Perfect。这比我上面的
match
语句要简单得多!谢谢