计算自定义数据的长度
Calculate length of custom data
我每天都在学习 Haskell。这时候想抓取一个自定义数据的size做进一步的处理。假设我有:
data LetterAlphabet = L1 | L2 | L3 | L4 deriving (Show,Enum,Bounded)
fun :: (Bounded a, Enum a) => a -> Int
fun a = 1 + fromEnum (maxBound :: LetterAlphabet)
它可以工作,但我必须明确指出数据类型。我尝试使用 (maxBound :: typeof a) 和类似的方法,但没有成功。
您可以通过使用 asTypeOf :: a -> a -> a
来使用技巧,其中 returns 第一个项目但强制该项目与第二个参数属于同一类型,因此:
fun :: (Bounded a, Enum a) => a -> Int
fun a = 1 + fromEnum (<strong>asTypeOf</strong> maxBound <strong>a</strong>)
但更优雅的方法是使用 TypeApplications
extension:
{-# LANGUAGE AllowAmbiguousTypes, ScopedTypeVariables, TypeApplications #-}
fun :: forall a . (Bounded a, Enum a) => Int
fun = 1 + fromEnum (maxBound @a)
那么这个可以作为fun @LetterAlphabet
)。因此我们只指定类型,我们不传递该类型的变量。
我每天都在学习 Haskell。这时候想抓取一个自定义数据的size做进一步的处理。假设我有:
data LetterAlphabet = L1 | L2 | L3 | L4 deriving (Show,Enum,Bounded)
fun :: (Bounded a, Enum a) => a -> Int
fun a = 1 + fromEnum (maxBound :: LetterAlphabet)
它可以工作,但我必须明确指出数据类型。我尝试使用 (maxBound :: typeof a) 和类似的方法,但没有成功。
您可以通过使用 asTypeOf :: a -> a -> a
来使用技巧,其中 returns 第一个项目但强制该项目与第二个参数属于同一类型,因此:
fun :: (Bounded a, Enum a) => a -> Int
fun a = 1 + fromEnum (<strong>asTypeOf</strong> maxBound <strong>a</strong>)
但更优雅的方法是使用 TypeApplications
extension:
{-# LANGUAGE AllowAmbiguousTypes, ScopedTypeVariables, TypeApplications #-}
fun :: forall a . (Bounded a, Enum a) => Int
fun = 1 + fromEnum (maxBound @a)
那么这个可以作为fun @LetterAlphabet
)。因此我们只指定类型,我们不传递该类型的变量。