Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# - For Loop question in F#

Tags:

function

f#

I would like to write this kind of program (this is a simple example to explain what i would like to do) :

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

like image 432
katter75 Avatar asked Jan 22 '26 01:01

katter75


1 Answers

Instead of using separate variables for individual matrices, you could use a list of matrices:

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

If your matrices are hard-coded (as in your example), then you can initialize the list using the notation above. If they are calculated in some way (e.g. as a diagonal or permutations or something like that), then there is probably better way to create the list, either using List.init or using similar function.

Once you have a list, you can iterate over it using a for loop:

for product in products do
  printfn "%A" product 

(In your sample, you're not using the index for anything - but if you needed indexing for some reason, you could create an array using [| ... |] and then access elements using products.[i])

like image 98
Tomas Petricek Avatar answered Jan 23 '26 16:01

Tomas Petricek