class 中的多个类型同义词

Multiple type synonyms in a class

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

{-# 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 Whosebug.hs 
[1 of 1] Compiling Main             ( Whosebug.hs, interpreted )

Whosebug.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会很好。

您可以从 class:

中单独定义类型同义词
{-# 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 的缩写,但它可能比这更复杂。