F# - 在F#中的For循环问题

3

我想编写这样的程序(这只是一个简单的示例,用于解释我想要做什么):

//  #r "FSharp.PowerPack.dll" 

open Microsoft.FSharp.Math

// Definition of my products

let product1 = matrix [[0.;1.;0.]]

let product2 = matrix [[1.;1.;0.]]

let product3 = matrix [[1.;1.;1.]]

// Instead of this (i have hundreds of products) : 

printfn "%A" product1

printfn "%A" product2

printfn "%A" product3

// I would like to do something like this (and it does not work):

for i = 1 to 3 do

printfn "%A" product&i

Thank you in advance !!!!!


1
你可以将 product1productN 添加到列表 lst 中,然后执行以下代码:for prod in lst do printfn "%A" prod。这是你想要的吗? - Daniel
2个回答

12

不必使用单独的变量来存储矩阵,可以使用一个矩阵列表:

let products = [ matrix [[0.;1.;0.]] 
                 matrix [[1.;1.;0.]] 
                 matrix [[1.;1.;1.]] ]
如果你的矩阵是硬编码(就像你的例子一样),那么你可以使用上述符号初始化列表。如果它们以某种方式被计算出来(例如作为对角线或排列之类的东西),那么创建列表的更好方法可能是使用List.init或类似函数。

一旦你有了一个列表,你可以使用for循环遍历它:

for product in products do
  printfn "%A" product 

在你的示例中,你没有使用索引 - 但是如果你出于某种原因需要使用索引,你可以使用 [| ... |] 创建一个数组,然后使用 products.[i] 访问元素。


谢谢,非常完美!我将使用索引和数组示例... - katter75
请注意,直接使用.[i]索引在列表上也可以工作,但这可能会以O(n)的性能剖面而不是数组的O(1)为代价。 - David Grenier
@katter75:如果您的问题已经得到了满意的回答,请不要忘记将答案选择为“正确答案”。 - Ankur

1

你也可以这样做:

matrix    [ [ 0.; 1.; 0. ];
            [ 1.; 1.; 0. ];
            [ 1.; 1.; 1. ]; ]
    |> Seq.iter(fun p -> printf "%A" p)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接