I'm trying to make a data type in Haskell that will only match lowercase chars, but not uppercase chars. I'm looking for something like this:
data LowerChar = [a..z]
Since there are only 26 characters in that interval, you can represent your type as a finite type of 26 values, using e.g. Data.Finite
:
{-# LANGUAGE DataKinds #-}
import Data.Finite
import Data.Char
newtype Letter = Letter{ getLetterIndex :: Finite 26 }
toLowerChar :: Letter -> Char
toLowerChar = chr . (+ ord 'a') . fromIntegral . getFinite . getLetterIndex
fromLowerChar :: Char -> Maybe Letter
fromLowerChar = fmap Letter . packFinite . fromIntegral . subtract (ord 'a') . ord
Of course, you can interpret the same type into uppercase letters as well if you want to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With