尝试使用hmatrix创建零marix。 出于某种原因,当我在命令行上尝试此操作时,它可以工作:
buildMatrix 2 3 (\(r,c) -> fromIntegral 0)
然而,当我尝试在我的代码中做同样的事情时:
type Dim = (Int, Int)
buildFull :: Matrix Double -> Vector Int -> Vector Int -> Dim -> Int
buildFull matrix basic nonbasic (m, n) = do
-- Build mxn matrix of zeroes
let f = buildMatrix m n (\(r,c) -> fromIntegral 0)
m
失败了:
Pivot.hs:23:17:
Ambiguous type variable `a0' in the constraints:
(Element a0) arising from a use of `buildMatrix'
at Pivot.hs:23:17-27
(Num a0) arising from a use of `fromIntegral' at Pivot.hs:23:44-55
Probable fix: add a type signature that fixes these type variable(s)
In the expression: buildMatrix m n (\ (r, c) -> fromIntegral 0)
In an equation for `f':
f = buildMatrix m n (\ (r, c) -> fromIntegral 0)
In the expression:
do { let f = buildMatrix m n (\ (r, c) -> ...);
m }
Failed, modules loaded: none.
答案 0 :(得分:5)
您还可以使用Numeric.Container中的konst
:
import Numeric.LinearAlgebra
m = konst 0 (2,3) :: Matrix Double
v = konst 7 10 :: Vector (Complex Float)
答案 1 :(得分:3)
将fromIntegral 0
替换为0::Double
。否则,您要构建的矩阵类型是不受约束的。在提示符下,扩展的默认规则可能会为您解决该问题。
答案 2 :(得分:3)
type Dim = (Int, Int)
buildFull :: Matrix Double -> Vector Int -> Vector Int -> Dim -> Int
buildFull matrix basic nonbasic (m, n) = do
-- Build mxn matrix of zeroes
let f = buildMatrix m n (\(r,c) -> fromIntegral 0)
m
首先,要使用do
- 表示法,你需要一个monadic返回类型,所以即使修复了不明确的元素类型也不会编译(因为@Carl提醒我,这里可以只有一个表达式,因此不需要(>>=)
或(>>)
。
关于元素类型,在let-binding中,无法找出要使用的类型,fromIntegral
是否应返回Double
,Integer
或其他类型。通常,要使用的类型可以通过上下文中使用的表达式来推断。这里,f
没有使用,所以没有上下文。因此,在这种情况下,您必须通过签名指定类型,可以是
let f :: Matrix Double
f = buildMatrix m n (const 0)
或
let f = buildMatrix m n (\_ -> (0 :: Double))
如果您希望元素类型为Double
。