本文介绍了F#嵌套List.iter调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个F#功能,我想尝试改变一些参数并测试所有这些组合。这是正确的方法吗? (括号变得有点密集......):

I have an F# function and I want to try varying some of the parameters and testing all such combinations. Is this the right approach? (The parentheses get a bit dense...):

let MyFunc a b c x y z = 
  ...
  q


let UploadResult a b c x y z q =
  ...
  ()


let a = 5.0
let b = 0
let c = System.DateTime.Today
let xList = [-1.0; 0.0; 1.0]
let yList = [2; 4; 6; 8; 10]
let zList = [0.1; 0.001]

xList  |> List.iter (fun x ->
(yList |> List.iter (fun y ->
(zList |> List.iter (fun z ->
MyFunc a b c x y z 
|> UploadResult a b c x y z ))) ))
|> ignore

所以我想上传3x5x2 = 30个结果,然后写得很好。谢谢你的建议。

So I want to upload 3x5x2=30 results, and write it nicely. Thanks for any advice.

推荐答案

实际上,您的主要目标是创建跨产品(或笛卡儿多个列表的产品),在F#开发人员中有几个选项被认为是良好实践:

In fact, your primary goal is creating a Cross-Product (or Cartesian Product) of several lists, and there are several options considered "good practice" among F# developers:

1。 (已删除 -comprehension,因为其他答案已经建议了这一点)

1. (removed for-comprehension as other answer already suggested this)

2。使用计算表达式(在函数式编程世界的其余部分,通常称为 Monad ):

2. Use Computation Expressions (in the rest of Functional Programming world, it is often called Monad):

type Product () =
    member this.Bind (l,f) = List.collect f l    
    member this.Return n = [n]

let ret02 = Product() {
    let! x = xList
    let! y = yList
    let! z = zList
    MyFunc a b c x y z
    |> UploadResult a b c x y z
}

3。如果您只是担心括号,请使用高优先级,右关联反向管道,()

3. If you only worry about parentheses, use the high precedence, right associative backward pipe, (more info)

let inline (^<|) f a = f a

然后,您的代码需要进行最小的修改(尽管仍然不是很干净):

Then, your code would need a minimal modification (albeit still not very clean):

let ret03 =
    xList  |> List.iter ^<| fun x ->
    yList  |> List.iter ^<| fun y ->
    zList  |> List.iter ^<| fun z ->
        MyFunc a b c x y z
        |> UploadResult a b c x y z
        |> ignore

这篇关于F#嵌套List.iter调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 12:58