答案是肯定的,但有一点需要注意。 func 的类型是什么?看起来它的第一个参数是一个类型,而不是一个值。稍后再说……
派生Enum 使您能够列出连续的构造函数,而派生Bounded 使您能够获取此枚举的“第一个”和“最后一个”元素。
data Class = Class1
| Class2
| Class3
deriving (Show, Eq, Enum, Bounded)
然后,我们可以通过enumFromTo minBound maxBound(或只是[minBound .. maxBound])获取所有元素的列表。
但是,回到关于func 类型的最初问题。您需要传入一个类型作为参数。通常的做法是使用Proxy 和ScopedTypeVariables。
{-# LANGUAGE ScopedTypeVariables #-}
import Data.Proxy (Proxy(..))
func :: forall a. (Enum a, Bounded a, Show a) => Proxy a -> [String]
func Proxy = map show $ enumFromTo minBound (maxBound :: a)
在 GHCi 试试这个:
ghci> func (Proxy :: Proxy Class)
["Class1","Class2","Class3"]
ghci> func (Proxy :: Proxy Bool)
["True","False"]