繁体   English   中英

F# - 用于F#中的循环问题

[英]F# - For Loop question in 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

先感谢您 !!!!!

您可以使用矩阵列表,而不是为单个矩阵使用单独的变量:

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]访问元素products.[i]

你也可以这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM