yong
yong

Reputation: 3633

How to use Linear.V to write static type checked matrix operations (Haskell)?

I'm interested in using Linear.V from the Linear library to write matrix operations on sizes that are known at compile time. However, I'm not sure how to use this library. Where can I find more references on how to use it?

Upvotes: 2

Views: 181

Answers (1)

ocharles
ocharles

Reputation: 6070

This is a little tricky to ask without a bit more knowledge of what exactly you want to do, but I'll take a stab. Linear.V gives you n-dimensional vectors for any n. In linear, matrices are defined as vectors-of-vectors - Linear.Matrix defines the operations on such values. Linear.Matrix works over various sizes of matrix by being parameterized over two functors, and Linear.V is indeed a Functor so we're good to use those operations.

The following boring example shows how you could work with Linear.V:

{-# LANGUAGE DataKinds #-}
import Linear
import Linear.V
import Data.Vector

identity :: V 2 (V 2 Float)
identity = V (fromList [ V (fromList [1, 0]), V (fromList [0, 1]) ])

calculation :: V 2 (V 2 Float)
calculation = identity !*! identity

It's boring in that it just calculates the product of two identity matrices, but it should give you an idea how to put these pieces together. I'm using GHC 7.6+ type literals to specify that identity is a 2x2 matrix.

Note that using the V constructor is somewhat dangerous - it allows you to "lie" about the size of the vector. For example, if you do the following:

identity :: V 2 (V 2 Float)
identity = V (fromList [ V (fromList [1, 0]) ])

things are likely to go very wrong. It's safer to use fromVector, or perhaps tabulate (tabulate uses the representation of V - which is basically a function from element index to its value).

Upvotes: 4

Related Questions