代码之家  ›  专栏  ›  技术社区  ›  Rafael S. Calsaverini

在Haskell中提升类实例

  •  13
  • Rafael S. Calsaverini  · 技术社区  · 16 年前

    有没有一种方法可以轻松地“提升”Haskell中的类实例?

    我经常需要为一些类创建Num实例,这些类只是通过类型构造函数“提升”Num结构,如下所示:

    data SomeType a = SomeCons a
    
    instance (Num a)=>Num SomeCons a where
        (SomeCons x) + (SomeCons y) = SomeCons (x+y)
        negate (SomeCons x) = SomeCons (negate x)
        -- similarly for other functions.
    

    有没有办法避免这个样板文件并自动“提升”这个Num结构?当我试图学习存在性时,我通常不得不对Show和其他类执行此操作,而编译器不允许我使用 deriving(Show)

    3 回复  |  直到 15 年前
        1
  •  19
  •   Greg Bacon    16 年前

    这里需要的是广义的newtype派生扩展:

    {-# LANGUAGE GeneralizedNewtypeDeriving #-}
    
    module Main where
    
    newtype SomeType a = SomeCons a deriving (Num, Show, Eq)
    
    main = do
      let a = SomeCons 2
          b = SomeCons 3
      print $ a + b
    

    输出:

    *Main> main
    SomeCons 5
    
        2
  •  5
  •   Raoul Supercopter    16 年前

    Extensions to the deriving mecanism 这些修改通常显示为将来的标准语言扩展(如上所示) haskell' wiki

    {-# GeneralizedNewtypeDeriving #-}
    

    然后像往常一样在newtype声明中使用派生

    data SomeType a = SomeCons a deriving (Num)
    
        3
  •  1
  •   Don Stewart    16 年前

    广义newtypedering

    推荐文章