Last active
June 25, 2021 14:50
-
-
Save carymrobbins/2b119241162077037f35e6410a2a07e9 to your computer and use it in GitHub Desktop.
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
| #!/usr/bin/env stack | |
| {- stack | |
| --resolver lts-15.6 | |
| --install-ghc runghc | |
| -} | |
| -- | Demonstrates the 'showName' function. | |
| -- | |
| -- @TemplateHaskellQuotes@ is enabled so we can use the @'name@ syntax. | |
| -- @DuplicateRecordFields@ is enabled to show that we handle name mangling. | |
| {-# LANGUAGE TemplateHaskellQuotes #-} | |
| {-# LANGUAGE DuplicateRecordFields #-} | |
| {-# OPTIONS_GHC -Wall #-} | |
| import qualified Language.Haskell.TH.Syntax as TH | |
| -- | Gets the given identifier name as a 'String'. | |
| -- | |
| -- If @DuplicateRecordFields@ is enabled, detects the names in the form of | |
| -- @$sel:name:Type@ and extracts the @name@. | |
| showName :: TH.Name -> String | |
| showName (TH.Name (TH.OccName s) _) = | |
| case s of | |
| '$' : _ -> takeWhile (/= ':') (drop 5 s) | |
| _ -> s | |
| data Foo = Foo | |
| { bar :: Int | |
| , baz :: Char | |
| } | |
| spam :: Int | |
| spam = 1 | |
| class Eggs a where | |
| egg :: a | |
| main :: IO () | |
| main = do | |
| putStrLn $ showName 'bar | |
| putStrLn $ showName 'baz | |
| putStrLn $ showName 'spam | |
| putStrLn $ showName 'egg |
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
| % ./showName.hs | |
| bar | |
| baz | |
| spam | |
| egg |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment