一个类中的多个类型同义词

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

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

回答

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

{-# 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短期的,但它可以比变得更加复杂。


以上是一个类中的多个类型同义词的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>