Created
August 31, 2026 02:23
-
-
Save minoki/09ea1074bdbb6ec50bb7da08b6cbe67d to your computer and use it in GitHub Desktop.
An example of QualifiedStrings to validate the string literal at compile-time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {-# LANGUAGE DataKinds #-} | |
| {-# LANGUAGE TypeFamilies #-} | |
| {-# LANGUAGE RequiredTypeArguments #-} | |
| {-# LANGUAGE UndecidableInstances #-} | |
| module AsciiOnly where | |
| import Data.Kind | |
| import Data.Type.Ord | |
| import Data.Proxy | |
| import GHC.TypeLits | |
| type IsAsciiOnly :: Symbol -> Constraint | |
| type IsAsciiOnly s = IsAsciiOnlyHelper (UnconsSymbol s) | |
| type IsAsciiOnlyHelper :: Maybe (Char, Symbol) -> Constraint | |
| type family IsAsciiOnlyHelper m where | |
| IsAsciiOnlyHelper Nothing = () | |
| IsAsciiOnlyHelper (Just '(c, rest)) = (c <= '\x7f', IsAsciiOnly rest) | |
| fromString :: forall (s :: Symbol) -> (IsAsciiOnly s, KnownSymbol s) => String | |
| fromString s = symbolVal (Proxy @s) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {-# LANGUAGE QualifiedStrings #-} | |
| import qualified AsciiOnly | |
| main :: IO () | |
| main = do | |
| putStrLn AsciiOnly."Hello world!" | |
| -- putStrLn AsciiOnly."🤔" -- type error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment