【问题标题】:Type class instance redefining类型类实例重新定义
【发布时间】:2017-08-31 18:14:08
【问题描述】:
  1. 我试图回答这个问题: "给定代数数据类型

    data Maybe a = Nothing | Just a
    

    选择正确的实例声明,表明类型构造函数MaybeMonad。”(摘自此处:“DelftX: FP101x Introduction to Functional Programming”。

  2. 我试图回答它的方法是依次编译每个可能的答案,例如,这个:

    instance Monad Maybe where
               return x = Just x
               Nothing >>= _ = Nothing
               (Just x ) >>= f = f x
    
  3. 我无法编译它,因为它已经在前奏中定义了。

    HwEx9.hs:16:10: error:
        Duplicate instance declarations:
          instance Monad Maybe -- Defined at HwEx9.hs:16:10
          instance Monad Maybe -- Defined in `GHC.Base'
    

我的问题是:如何编译它?

【问题讨论】:

  • 最简单的方法:定义自己的Maybe-like 类型。
  • 没有办法避免为给定类型导入类型类实例。 (进一步查看stackoverflow.com/a/8731340/6476589
  • 改成MyMaybe?

标签: haskell duplicates instance monads redefinition


【解决方案1】:

我只是模仿Maybe 数据类型,例如:

data Maybe' a = Just' a | Nothing' deriving Show

instance Monad Maybe' where
    return x = Just' x
    Nothing' >>= _ = Nothing'
    (Just' x) >>= f = f x

ghc 的最后一个版本中,这将失败,因为最后一个版本要求您也实现应用程序。我们可以这样做:

instance Applicative Maybe' where
    pure = Just'
    (Just' f) <*> (Just' x) = Just' (f x)
    _ <*> _ = Nothing'

Applicative 要求类型是Functor 的实例,所以我们可以这样实现:

instance Functor Maybe' where
    fmap f (Just' x) = Just' (f x)
    fmap _ Nothing' = Nothing'

然后它将编译。这种方法的优点还在于我们可以很容易地比较两个Maybe monad,例如:

*Main> Just 2 >>= (\x -> Just (x+1))
Just 3
*Main> Just' 2 >>= (\x -> Just' (x+1))
Just' 3

【讨论】:

  • 按照您的建议(谢谢),您将如何模仿列表 Monad,给出如下:instance Monad [] where return x = [x] xs >>= f = concat (map f xs )
  • data List' = Empty' | Cons' a (List' a).
  • 不应该是:数据列表'a = Empty' | Cons' a (List' a) (感谢您的快速回答)。
  • 它不起作用:这是代码(取自此处:schoolofhaskell.com/school/starting-with-haskell/…)数据列表 a = Nil | Cons a (List a) instance (Show a) => Show (List a) where show Nil = "" show (Cons x xs) = show x ++ ", " ++ show xs instance Functor List where fmap f Nil = Nil fmap f (Cons x xs) = Cons (f x) (fmap f xs) 实例 Applicative List where pure = Cons x Nil (List f) (List x) = List (f x) _ _ = Nil (错误:不在范围内:数据构造函数“列表”)
  • 它不起作用:这是代码(取自此处:schoolofhaskell.com/school/starting-with-haskell/…)数据列表 a = Nil | Cons a (List a) instance (Show a) => Show (List a) where show Nil = "" show (Cons x xs) = show x ++ ", " ++ show xs instance Functor List where fmap f Nil = Nil fmap f (Cons x xs) = Cons (f x) (fmap f xs) 实例 Applicative List where pure = Cons x Nil (List f) (List x) = List (f x) _ _ = Nil (错误:不在范围内:数据构造函数“列表”)
猜你喜欢
  • 2021-01-14
  • 1970-01-01
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 2019-06-30
  • 2020-03-21
相关资源
最近更新 更多