15

在 Haskell 中,有没有办法限制 monadM aa满足类型类约束?

我正在将概率建模示例F#转换为Haskell。但是,在 Haskell 中,我省略了,support因为它会更改data Distribution adata (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。有没有办法让我拥有一个 monad Distribution,但强制限制(Ord a)这个 monad?我试过:

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.

所以它有一种方法可以有一个 monad M a,但是a用一个约束来限制Ord a?

谢谢。

4

3 回答 3

13

看来我在 Haskell 中遇到了一个众所周知的问题。我通过谷歌搜索“restricted monads”找到了许多解决方法这种解决方案似乎破坏性最小。不过,就我的目的而言,这似乎有点过头了。正如 Revolucent 所建议的那样,我想我会保持monad 的通用性,并通过受限功能简化支持。Distribution

于 2008-12-19T01:04:39.900 回答
10

我对此的理解是您根本不能,因为 monad 旨在泛化所有类型,而不是某些类型的受限子集,例如(Ord a).

您可以简单地限制使用该单子类型的函数,而不是限制M a单子类型,例如,

foo :: Ord a => Int -> M a

事实上,最好保持类型尽可能通用,并且只使用类型类来限制功能。

等等

于 2008-12-18T22:53:42.410 回答
3

查看Martin Erwig 的图书馆,PFP

The PFP library is a collection of modules for Haskell that facilitates probabilistic functional programming, that is, programming with stochastic values. The probabilistic functional programming approach is based on a data type for representing distributions. A distribution represent the outcome of a probabilistic event as a collection of all possible values, tagged with their likelihood.

于 2008-12-19T01:27:59.837 回答