开发者

F#: how to create matrix of elements of any other type except Double

开发者 https://www.devze.com 2022-12-24 08:34 出处:网络
I\'m a beginner in F#. I know that there is the way to create Double Matrix using PowerPack.dll: let B = matrix [ [ 1.0; 7.0 ];

I'm a beginner in F#. I know that there is the way to create Double Matrix using PowerPack.dll:

let B = matrix [ [ 1.0; 7.0 ];
                 [ 1.0开发者_如何学C; 3.0 ] ]

How can I create matrix with elements of my own type (for example with [,] instead of Double), so it would look like:

let B = matrix [ [ [1,2]; [3,4] ];
                 [ [7,8]; [5,6] ] ]


I agree that matrix should be mainly used when working with numbers. The standard non-generic matrix type (which you can create using the matrix function) works with numbers of type float. If you want to work with other numeric types, you can use Matrix.Generic module, which contains functionality for working with generic matrices (containing any types).

You can use generic matrix for storing tuples as well (if you want). A generic matrix can be created using the ofList function. You can also define a function for this to get a nicer syntax:

let anymatrix = Matrix.Generic.ofList
let B = anymatrix [ [ [1,2]; [3,4] ]; 
                    [ [7,8]; [5,6] ] ]

To work with generic matrices, you can use the Matrix.Generic module:

let Bt = Matrix.Generic.transpose B

Typically, you'll use matrices only with numeric types, because many of the operations require some arithmetics in order to work. This will work for all basic numeric types (such as int) and you can also provide arithmetics for your own type using GlobalAssociations discussed here.

However, if you want to simply store some values then there are other (more suitable) data types. You can also use Array2D which represents a mutable two-dimensional array.


Tomas already gives a good answer. I will comment a bit here.

Let's see some source code in matrix.fsi from PowerPack:

type matrix = Matrix<float>

so matrix is a concrete type instantiated from the meta type Matrix. You could also use

type intmatrix = Matrix<int>

to define your int matrix type.

but to use something like:

let B = matrix [ [ 1.0; 7.0 ];
                 [ 1.0; 3.0 ] ]

We need another function called matrix, whose deceleration as

val matrix : seq<#seq<float>> -> matrix

let's see its implementation in matrix.fs:

let matrix ll = Microsoft.FSharp.Math.Matrix.ofSeq ll

while Microsoft.FSharp.Math.Matrix module is for double(in f# float) matrix, Microsoft.FSharp.Math.Matrix.Generics is for generic matrix. You can implement your intmatrix 'constructor'.

put it together:

type intmatrix = Matrix<int>
let intmatrix ll = Matrix.Generic.ofSeq  ll
let C = intmatrix [ [1;2]; [3;4] ];


Matrix is a particularly mathematical type for working with numbers.

If you just want to arrange arbitrary elements in a rectangular shape, use standard F# lists or arrays.

0

精彩评论

暂无评论...
验证码 换一张
取 消