2011-05-09 33 views
7

我正在嘗試使用Numeric.AD和自定義Expr類型。我希望計算 用戶輸入表達式的符號梯度。以恆定 表達的初審工作得很好:Numeric.AD和打字問題

calcGrad0 :: [Expr Double] 
calcGrad0 = grad df vars 
    where 
    df [x,y] = eval (env [x,y]) (EVar "x"*EVar "y") 
    env vs = zip varNames vs 
    varNames = ["x","y"] 
    vars = map EVar varNames 

這工作:

>calcGrad0 
[Const 0.0 :+ (Const 0.0 :+ (EVar "y" :* Const 1.0)),Const 0.0 :+ (Const 0.0 :+ (EVar "x" :* Const 1.0))] 

但是,如果我拉的表達了作爲一個參數:

calcGrad1 :: [Expr Double] 
calcGrad1 = calcGrad1' (EVar "x"*EVar "y") 
calcGrad1' e = grad df vars 
    where 
    df [x,y] = eval (env [x,y]) e 
    env vs = zip varNames vs 
    varNames = ["x","y"] 
    vars = map EVar varNames 

我得到

Could not deduce (a ~ AD s (Expr a1)) 
from the context (Num a1, Floating a) 
    bound by the inferred type of 
      calcGrad1' :: (Num a1, Floating a) => Expr a -> [Expr a1] 
    at Symbolics.hs:(60,1)-(65,29) 
or from (Mode s) 
    bound by a type expected by the context: 
      Mode s => [AD s (Expr a1)] -> AD s (Expr a1) 
    at Symbolics.hs:60:16-27 
    `a' is a rigid type variable bound by 
     the inferred type of 
     calcGrad1' :: (Num a1, Floating a) => Expr a -> [Expr a1] 
     at Symbolics.hs:60:1 
Expected type: [AD s (Expr a1)] -> AD s (Expr a1) 
    Actual type: [a] -> a 
In the first argument of `grad', namely `df' 
In the expression: grad df vars 

我如何獲得ghc接受此?

+1

Saizan已經在#haskell解決了這個問題。我在eval的調用中只是錯過了fmap lift e。 – aleator 2011-05-09 14:54:00

回答

5

我的猜測是你忘記申請liftExpr轉換爲AD s Expr

如果您有興趣使用ad包進行符號區分。 Lennart Augustsson的traced包運作良好。

1

當GHC不能推導一個有效函數的類型相等簽名時,就像你的情況一樣,解決方法是給函數一個類型簽名。我不知道這個庫的接口。但是,我的猜測是正確的簽名是calcGrad1 :: (Num a, Floating a) => Expr a -> [Expr a]