首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用hmatrix构建零点矩阵?

如何使用hmatrix构建零点矩阵?
EN

Stack Overflow用户
提问于 2011-12-09 01:09:34
回答 3查看 715关注 0票数 2

尝试使用hmatrix创建一个零矩阵。出于某些原因,当我在命令行上尝试时,它可以工作:

代码语言:javascript
复制
buildMatrix 2 3 (\(r,c) -> fromIntegral 0)

然而,当我尝试在我的代码中做同样的事情时:

代码语言:javascript
复制
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

它失败了:

代码语言:javascript
复制
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.
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-12-09 01:20:50

代码语言:javascript
复制
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-notation,您需要一个一元返回类型,这样即使在修复了不明确的元素类型之后也不会进行编译( @Carl提醒我,这里只有一个表达式,所以不需要(>>=)(>>) )。

关于元素类型,在let绑定中,没有办法知道应该使用哪种类型,fromIntegral应该返回DoubleInteger还是其他任何类型。通常,要使用的类型可以通过使用它的表达式从上下文中推断出来。在这里,没有地方使用f,所以没有上下文。因此,在这种情况下,您必须通过签名指定类型,这可以是

代码语言:javascript
复制
let f :: Matrix Double
    f = buildMatrix m n (const 0)

代码语言:javascript
复制
let f = buildMatrix m n (\_ -> (0 :: Double))

如果您希望元素类型为Double

票数 3
EN

Stack Overflow用户

发布于 2011-12-09 02:12:46

您也可以使用Numeric.Container中的konst

代码语言:javascript
复制
import Numeric.LinearAlgebra

m = konst 0 (2,3) :: Matrix Double

v = konst 7 10 :: Vector (Complex Float)
票数 5
EN

Stack Overflow用户

发布于 2011-12-09 01:17:35

0::Double替换fromIntegral 0。否则,您想要构建的矩阵类型将受到不足的约束。在提示符下,扩展的默认规则可能正在为您解决这个问题。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8434808

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档