haskellghclanguage-extension

Is there a GHC extension for enabling overloaded character literals?


I am aware that there is a GHC extension, OverloadedStrings, which allows string literals (delimited by ") to become polymorphic, similar to the built-in behavior for number literals.

My question is: is there a GHC extension that allows single character literals (delimited by ') to become polymorphic in an analogous way?


Solution

  • Not as of GHC 8.8, but you can use the QuasiQuotes extension to get pretty far. Here is an example of a quasiquote which only accepts an ascii character and converts it to its byte representation.

    import Language.Haskell.TH
    import Language.Haskell.TH.Quote
    import Language.Haskell.TH.Syntax
    
    import Data.Word (Word8)
    import Data.Char (isAscii)
    
    asciiByte :: QuasiQuoter
    asciiByte = QuasiQuoter
      { quoteExp = \str -> case str of
                             [c] | isAscii c -> lift (fromIntegral (fromEnum c) :: Word8)
                             _ -> fail ("asciiByte: expects a single ascii character, got " ++ str) 
      , quotePat = \_ -> fail "asciiByte: only available for expressions"
      , quoteType = \_ -> fail "asciiByte: only available for expressions"
      , quoteDec = \_ -> fail "asciiByte: only available for expressions"
      }
    

    Then, you can use it as:

    ghci> [asciiByte|a|]
    97
    ghci> [asciiByte|é|]
    
    <interactive>:75:12: error:
        • asciiByte: expects a single ascii character, got é
        • In the quasi-quotation: [asciiByte|é|]
    ghci> [asciiByte|abc|]
    
    <interactive>:76:12: error:
        • asciiByte: expects a single ascii character, got abc
        • In the quasi-quotation: [asciiByte|abc|]