2011-12-08 108 views
2

嘗試使用hmatrix來創建零芯片。 出於某種原因,當我嘗試這個命令行,它的工作原理:如何使用hmatrix構建零矩陣?

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. 

回答

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 -notation,你需要一個單子返回類型,這樣就不會編譯甚至固定的曖昧元素類型(如我被@Carl提醒後,它會好起來的,而在這裏只有一個表達式,因此不需要(>>=)(>>))。

關於元素類型,在let-binding中,沒有辦法找出使用哪種類型,fromIntegral是否應返回Double,Integer或其他什麼。通常使用的類型可以通過上下文來推斷,也可以通過它所使用的表達式來推斷。這裏沒有使用f,所以沒有上下文。因此,在這種情況下,你必須指定一個簽名的類型,可以

let f :: Matrix Double 
    f = buildMatrix m n (const 0) 

let f = buildMatrix m n (\_ -> (0 :: Double)) 
,如果你想要的元素O型是 Double

+1

這並不完全正確,你需要一個單子結果類型使用做記號。事實上,除了在desugaring過程之後它們是很好的類型之外,符號不會對它所產生的表達式的形式引入任何約束。由於這隻會解除「讓...在......」,並且不以任何方式涉及>> =或>>運算符,所以這種情況不需要單點返回類型。 – Carl

+0

嗯..我得到'非法簽名模式:矩陣 - >雙f 使用-XScopedTypeVariables來允許它錯誤,如果我做第一種方法。 – drozzy

+0

另外'let f = buildMatrix mn 0 :: Double'似乎不工作:「無法匹配預期的類型'(Int,Int) - > a0' 與實際類型'Double' 在第三個參數'buildMatrix',即'(0 :: Double)' 在表達式中:buildMatrix mn(0 :: Double) 在'f'的等式中:f = buildMatrix mn(0 :: Double) 失敗,加載模塊: 沒有。」 – drozzy

3

fromIntegral 0替換爲0::Double。否則,你想建立的矩陣是不受約束的。在提示時,擴展的違約規則可能會爲你解決這個問題。

5

您還可以使用konstNumeric.Container

import Numeric.LinearAlgebra 

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

v = konst 7 10 :: Vector (Complex Float)