将monad限制为一个类型类

将monad限制为一个类型类

本文介绍了将monad限制为一个类型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Haskell中,有没有办法限制monad M a ,这样 a 满足一个类型约束?



我正在翻译,从到。然而,在Haskell中,我省略了 support ,因为它会将数据分配a 更改为 data( Ord a)=>分配一个。有了这个变化,我得到了以下错误:

  ... probabilisticModeling.hs:42:13:
不是从上下文()中得出的($ a
$ b)在...中使用`always'
的概率probabilisticModeling.hs:42:13-18
可能的修正:
在'return'类型签名的上下文中添加(Ord a)
在表达式中:always
在'return'的定义中:return = always
在`Monad Distribution'

确实,的类型总是 / return 是:(Ord a)=> a - >分配一个。有没有一种方法可以让monad Distribution ,但是在这个monad上强制约束(Ord a)?我尝试过:

pre $ $ $ $ $ $ $实例Monad分布其中
(>> =)=绑定
return: :(Ord a)=> a - >发行a = always

但是我收到错误:
$ b $

return ::(Ord a )=> a - >分发a =总是
失败,模块加载:无。

所以有办法让monad M a ,但限制 a 的约束,如 Ord a



谢谢。

解决方案

我对此的理解是你根本无法做到,因为monad是为了可以概括为所有类型,而不是某些限制子类型,如(Ord a)



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

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

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



等。


In Haskell, is there a way to restrict a monad M a so that a satisfy a type class constraint?

I am translating the probabilistic modeling example from F# to Haskell. However, in Haskell, I omitted support because it would change data Distribution a to data (Ord a) => Distribution a. With this change, I get the following error:

...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'

Indeed, the type of always/return is: (Ord a) => a -> Distribution a. Is there a way I can have a monad Distribution, but force the constraint (Ord a) on this monad? I tried:

instance Monad Distribution where
    (>>=) = bind
    return :: (Ord a) => a -> Distribution a = always

But I get the error:

...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.

So it there a way to have a monad M a, but restrict the a with a constraint such as Ord a?

Thanks.

解决方案

My understanding of this is that you simply cannot, because a monad is meant to be generalized over all types, not some restricted subset of types such as (Ord a).

Instead of restricting the monadic type M a, you can simply restrict functions which use that monadic type, e.g.,

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

In fact, it is preferable to keep types as general as possible and use type classes only to restrict functions.

etc.

这篇关于将monad限制为一个类型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:28