如何在Haskell中使用Linear库创建矩阵

时间:2017-12-23 13:48:27

标签: haskell linear-algebra

Linear的documentation显示如何使用V1,V2,V3,V4函数创建矢量和矩阵,以创建尺寸为1,2,3,4的矢量。但我想使用具有更多元素的矩阵。

矩阵乘法example使用函数fromList显示和示例。

V2 (fromList [(1,2)]) (fromList [(2,3)]) !*! fromList [(1,V3 0 0 1), (2, V3 0 0 5)]

但我似乎无法在线性库中找到该功能。我如何创建具有任意尺寸的双值矩阵(例如5x6)?

1 个答案:

答案 0 :(得分:3)

查看(!*!)的类型

(!*!) :: (Functor m, Foldable t, Additive t, Additive n, Num a)
      => m (t a) -> t (n a) -> m (n a)

此处的重要约束是Additive,因此请查看其实例

instance Additive []
instance Additive Vector -- ordinary, unsized vectors from the vectors package
instance Additive V0
instance Additive V1
instance Additive V2
instance Additive V3
instance Additive V4 -- Sized vectors from linear up to n = 4
instance Dim n => Additive (V n) -- Vectors of arbitrary dimension where the size is given by a type level number n
-- plus other instances

所以你可以使用嵌套列表:

m :: [[Int]]
m = [ [ 0,1,2,3,4 ],
      [ 1,2,3,4,0 ],
      [ 2,3,4,0,1 ],
      [ 3,4,0,1,2 ],
      [ 4,0,1,2,3 ] ]

msq :: [[Int]]
msq = m !*! m

或嵌套Vectors

import Data.Vector(Vector)
import qualified Data.Vector as V

mv :: Vector (Vector Int)
mv = V.fromList $ V.fromList <$> m

mvsq :: Vector (Vector Int)
mvsq = mv !*! mv

或混合搭配:

mvl :: Vector [Int]
mvl = V.fromList m
mlv :: [Vector Int]
mlv = V.fromList <$> m

mvlmlv :: Vector (Vector Int)
mvlmlv = mvl !*! mlv

您可以使用V来跟踪尺寸:

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

mV :: V 5 (V 5 Int) -- GHC.TypeLits.Nat literals
mV = fromJust $ fromVector $ fromJust <$> fromVector <$> mv
mVsq :: V 5 (V 5 Int)
mVsq = mV !*! mV -- does not compile in case of dimension mismatch