我正在尝试编写一些Haskell代码来表示现有库(HLearn)中的负二项分布。据我所知,HLearn要求模型参数(在这种情况下为负二项分布的r值)作为表示分布的类型类中的类型级自然数输入。我的问题是,当我尝试使用sing来访问参数的运行时值时,我得到一个类似的相关错误。
相关代码已注释
-- | Negative binomial distribution
{-# LANGUAGE
GeneralizedNewtypeDeriving,
TypeFamilies,
DataKinds,
KindSignatures #-}
module HLearn.Models.Distributions.Univariate.NegativeBinomial
(NegativeBinomial
)
where
import GHC.TypeLits
import HLearn.Algebra
import HLearn.Models.Distributions.Common
import HLearn.Models.Distributions.Univariate.Internal.Moments
newtype NegativeBinomial (r::Nat) prob dp = NegativeBinomial { moments :: (Moments3 dp) }
deriving (Read, Show, Eq, Ord, Monoid, Group)
instance (Num dp) => HomTrainer (NegativeBinomial r prob dp) where
type Datapoint (NegativeBinomial r prob dp) = dp
train1dp dp = NegativeBinomial $ train1dp dp
instance (Num dp) => Probabilistic (NegativeBinomial r prob dp) where
type Probability (NegativeBinomial r prob dp) = prob
-- The function in question
negbin_p :: (SingI r, Integral dp, Fractional prob) => NegativeBinomial r prob dp -> prob
negbin_p (NegativeBinomial moments) = ((fromIntegral $ m0 moments)/(fromIntegral $ m1 moments)) * rval
where
rval = fromSing (sing :: Sing r) -- This is the code that is reported as causing errors
我得到的错误是:
src\HLearn\Models\Distributions\Univariate\NegativeBinomial.hs:33:24:
Could not deduce (SingE * (Kind *) prob)
arising from a use of `fromSing'
from the context (SingI Nat r, Integral dp, Fractional prob)
bound by the type signature for
negbin_p :: (SingI Nat r, Integral dp, Fractional prob) =>
NegativeBinomial r prob dp -> prob
at src\HLearn\Models\Distributions\Univariate\NegativeBinomial.hs:30:13-89
Possible fix:
add an instance declaration for (SingE * (Kind *) prob)
In the expression: fromSing (sing :: Sing r)
In an equation for `rval': rval = fromSing (sing :: Sing r)
In an equation for `negbin_p':
negbin_p (NegativeBinomial moments)
= ((fromIntegral $ m0 moments) / (fromIntegral $ m1 moments))
* rval
where
rval = fromSing (sing :: Sing r)
src\HLearn\Models\Distributions\Univariate\NegativeBinomial.hs:33:34:
Could not deduce (SingI * r1) arising from a use of `sing'
from the context (SingI Nat r, Integral dp, Fractional prob)
bound by the type signature for
negbin_p :: (SingI Nat r, Integral dp, Fractional prob) =>
NegativeBinomial r prob dp -> prob
at src\HLearn\Models\Distributions\Univariate\NegativeBinomial.hs:30:13-89
Possible fix: add an instance declaration for (SingI * r1)
In the first argument of `fromSing', namely `(sing :: Sing r)'
In the expression: fromSing (sing :: Sing r)
In an equation for `rval': rval = fromSing (sing :: Sing r)
我做错了什么?
答案 0 :(得分:1)
感谢luqui指出了ScopedTypeVariables。将其添加到语言编译指示后,更新的工作代码是相同的,除了:
negbin_p :: forall r dp prob . (SingI r, Integral dp, Fractional prob) => NegativeBinomial r prob dp -> prob
negbin_p (NegativeBinomial moments) = ((fromIntegral $ m0 moments)/(fromIntegral $ m1 moments)) * rval
where
rval = fromIntegral $ fromSing (sing :: Sing r)