2011-08-30 125 views
3

我想编写这种程序的(这是一个简单的例子来解释我想做些什么):F# - For循环的问题在F#

// #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 

预先感谢您!!!! !

+1

您可以添加'produc t1'到'productN'到列表中,'lst'和do:'用于制作printfn“%A”prod'。那是你的追求? – Daniel

回答

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]

+0

谢谢你的完美!我将使用索引和数组示例... – katter75

+0

请注意,通过。[i]的直接索引也适用于列表,但它可能在O(n)中具有性能配置文件,而不是O(1)阵列。 –

+0

@ katter75:如果你的问题已经回答了你的期望,那么请不要忘记选择,然后回答为“正确”。 – Ankur

2

而且[| ... |],然后访问元素的数组,你可以那样做:

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