Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Last active June 25, 2021 14:50
Show Gist options
  • Select an option

  • Save carymrobbins/2b119241162077037f35e6410a2a07e9 to your computer and use it in GitHub Desktop.

Select an option

Save carymrobbins/2b119241162077037f35e6410a2a07e9 to your computer and use it in GitHub Desktop.
#!/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
% ./showName.hs
bar
baz
spam
egg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment