【发布时间】:2010-09-27 15:08:12
【问题描述】:
在 Haskell 中,有没有办法限制 monad M a 以使 a 满足类型类约束?
我正在将probabilistic modeling example 从F# 翻译成Haskell。但是,在 Haskell 中,我省略了 support,因为它会将 data Distribution a 更改为 data (Ord a) => Distribution a。通过此更改,我收到以下错误:
...probabilisticModeling.hs:42:13:
Could not deduce (Ord a) from the context ()
arising from a use of `always'
at ...probabilisticModeling.hs:42:13-18
Possible fix:
add (Ord a) to the context of the type signature for `return'
In the expression: always
In the definition of `return': return = always
In the instance declaration for `Monad Distribution'
确实,always/return 的类型是:(Ord a) => a -> Distribution a。有没有办法让我有一个单子Distribution,但在这个单子上强制约束(Ord a)?我试过了:
instance Monad Distribution where
(>>=) = bind
return :: (Ord a) => a -> Distribution a = always
但我得到了错误:
...probabilisticModeling2.hs:48:4:
Pattern bindings (except simple variables) not allowed in instance declarations
return :: (Ord a) => a -> Distribution a = always
Failed, modules loaded: none.
所以有办法拥有一个单子M a,但用Ord a之类的约束来限制a?
谢谢。
【问题讨论】:
标签: haskell types monads typeclass