代码之家  ›  专栏  ›  技术社区  ›  namin

将monad限制为类型类

  •  15
  • namin  · 技术社区  · 17 年前

    M a 因此 a 满足类型类约束?

    我正在翻译这本书 probabilistic modeling example F# 到 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.
    

    所以有一种方法可以得到单子 我是 A. 具有约束,例如 Ord a ?

    谢谢

    3 回复  |  直到 15 年前
        1
  •  13
  •   namin    17 年前

    看来我在哈斯克尔遇到了一个众所周知的问题。我 found many workarounds 通过 googling for "restricted monads" . This solutions Distribution monad-general,并按照revolcent的建议,通过受限函数简化支持。

        2
  •  10
  •   Gregory Higley    17 年前

    (Ord a) .

    M a ,您可以简单地限制使用该一元类型的函数,例如。,

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

    事实上,最好尽量保持类型的通用性,并且只使用类型类来限制函数。

        3
  •  3
  •   stites James    10 年前

    退房 Martin Erwig's library, PFP :

    PFP库是Haskell的一个模块集合,有助于概率函数编程,即使用随机值编程。概率函数规划方法基于表示分布的数据类型。分布将概率事件的结果表示为所有可能值的集合,并标记其可能性。