Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data type for only lowercase chars

Tags:

haskell

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]
like image 387
HYBR1D Avatar asked Dec 22 '22 23:12

HYBR1D


1 Answers

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.

like image 137
Cactus Avatar answered Jan 03 '23 07:01

Cactus