gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:43:39 25 4
gpt4 key购买 nike

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

{-# 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,但它可能比这更复杂。

关于haskell - 一个类中的多个类型同义词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68896181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com