【问题标题】:Multiple type synonyms in a class一个类中的多个类型同义词
【发布时间】:2021-08-24 00:54:11
【问题描述】:

有没有办法根据关联的类型同义词来定义类型同义词? (不确定我的术语是否正确。)

{-# LANGUAGE TypeFamilies #-}

class Reproductive a where

  -- | A sequence of genetic information for an agent.
  type Strand a

  -- | Full set (both strands) of genetic information for an organism.
  type Genome a = (Strand a, Strand a)

这是我收到的错误消息。

λ> :l stackOverflow.hs 
[1 of 1] Compiling Main             ( stackOverflow.hs, interpreted )

stackOverflow.hs:9:8: error:
    ‘Genome’ is not a (visible) associated type of class ‘Reproductive’
  |
9 |   type Genome a = (Strand a, Strand a)
  |        ^^^^^^
Failed, no modules loaded.

我可以在任何地方使用(Strand a, Strand a),但最好使用Genome a

【问题讨论】:

    标签: haskell type-families associated-types


    【解决方案1】:

    您可以将类型同义词与类分开定义:

    {-# LANGUAGE TypeFamilies #-}
      
    -- | Full set (both strands) of genetic information for an organism.
    type Genome a = (Strand a, Strand a)
    
    class Reproductive a where
    
      -- | A sequence of genetic information for an agent.
      type Strand a
    

    或者,如果您希望能够在某些情况下覆盖它,那么您可以这样定义它:

    {-# LANGUAGE TypeFamilies #-}
    
    class Reproductive a where
    
      -- | A sequence of genetic information for an agent.
      type Strand a
    
      -- | Full set (both strands) of genetic information for an organism.
      type Genome a 
      type Genome a = (Strand a, Strand a)
    

    这似乎是多余的,但是您可以将第一行type Genome a 视为签名,将第二行视为默认实现。在这种情况下,签名只是type Genome a :: * 或简称type Genome a,但它可以变得更复杂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      相关资源
      最近更新 更多