Home > front end >  Calculate length of custom data
Calculate length of custom data

Time:03-16

I'm learning Haskell one day at a time. At this time, I'd like to capture the size of a custom data to process it further. Say I have:

data LetterAlphabet = L1 | L2 | L3 | L4 deriving (Show,Enum,Bounded)

fun :: (Bounded a, Enum a) => a -> Int
fun a = 1   fromEnum (maxBound :: LetterAlphabet)

It works but I had to indicated the data type explicitly. I tried to use (maxBound :: typeof a) and similars, with no success.

CodePudding user response:

You can work with a trick by using asTypeOf :: a -> a -> a which returns the first item but forces that the item is of the same type as the second parameter, so:

fun :: (Bounded a, Enum a) => a -> Int
fun a = 1   fromEnum (asTypeOf maxBound a)

But a more elegant way is to work with the TypeApplications extension:

{-# LANGUAGE AllowAmbiguousTypes, ScopedTypeVariables, TypeApplications #-}

fun :: forall a . (Bounded a, Enum a) => Int
fun = 1   fromEnum (maxBound @a)

Then this can be used as fun @LetterAlphabet). We thus only specify the type, we do not pass a variable of that type.

  • Related