Obtaining TH.Name for '[] without -XTemplateHaskell - haskell

Is there a way to obtain (import from base modules or write expression) a value of type Language.Haskell.TH.Name that represents '[] without enabling -XTemplateHaskell?
A good reason to do so is that tools like hlint do not play well with TH and being able to avoid it therefore has a benefit. Then I could put a definition
nilName :: Name
nilName = '[]
in a separate file and import it, but this only makes sense if there is no standard name by which it can be imported or called. Furthermore, nilName cannot be used in pattern matches. Is there such a thing?

import Language.Haskell.TH.Syntax
nilName = mkNameG DataName "ghc-prim" "GHC.Types" "[]"
is an equivalent definition of nilName, even though it is ugly. It can be expanded to a form that admits to pattern matching yielding to
nilName = Name (OccName "[]") (NameG DataName (PkgName "ghc-prim") (ModName "GHC.Types"))
which is not nicer nor robust. It seems that the best route forward is a combination of the above nilName defined in a separate TH-enabled module together with (== nilName) instead of pattern matching.

Related

How to collect values spread throughout a Haskell codebase

I have a web application written in Haskell (using ghcjs on the client side and ghc on the server side) and I need a way to collect the CSS values which are spread throughout the modules. Currently I use a technique involving a CssStyle class and template haskell. When a module needs to export some CSS it creates a CssStyle instance for some type (the type has no significance except that it must be unique.) In the top level all the CssStyle instances are retrieved using the reifyInstances function from template haskell.
This approach has at least two drawbacks: You have to create meaningless types to attach the instances to, and you have to be sure all the instances are imported in the place where you scan and turn into real CSS. Can anyone think of a more beautiful way to collect data embedded in Haskell code?
================
Quelklef has requested some source code demonstrating the current solution:
{-# LANGUAGE AllowAmbiguousTypes, OverloadedStrings, MultiParamTypeClasses, TemplateHaskell, LambdaCase, FunctionalDependencies, TypeApplications #-}
import Clay
import Control.Lens hiding ((&))
import Data.Proxy
import Language.Haskell.TH
class CssStyle a where cssStyle :: Css
-- | Collect all the in scope instances of CssStyle and turn them into
-- pairs that can be used to build scss files. Result expression type
-- is [(FilePath, Css)].
reifyCss :: Q Exp
reifyCss = do
insts <- reifyInstances ''CssStyle [VarT (mkName "a")]
listE (concatMap (\case InstanceD _ _cxt (AppT _cls typ#(ConT tname)) _decs ->
[ [|($(litE (stringL (show tname))), $(appTypeE [|cssStyle|] (pure typ)))|] ]
_ -> []) insts)
data T1 = T1
instance CssStyle T1 where cssStyle = byClass "c1" & flexDirection row
data T2 = T2
instance CssStyle T2 where cssStyle = byClass "c2" & flexDirection column
-- Need to run this in the interpreter because of template haskell stage restriction:
--
-- > fmap (over _2 (renderWith compact [])) ($reifyCss :: [(String, Css)])
-- [("Main.T2",".c2{flex-direction:column}"),("Main.T1",".c1{flex-direction:row}")]
The point here is that any CssStyle instance from any module imported here will appear in this list, not only those defined locally.
Hmm...
I do not officially recommend your current approach. It's making use of typeclasses in a highly unorthodox way, so it's unlikely to act exactly as you like. As you've already noted, in order for it to work you need to make sure that all CssStyle instances are in scope, which is pretty arcane behaviour. Also, the current approach does not compose well, by which I mean that your css-related computation is all happening in the global context.
Unfortunately, I don't know of any canonical way to do what you want at compile-time.
However, I do have one idea. Most programs run in top-level "industrial" monads, and I'm assuming your program does as well. You could wrap your industrial monad with a new applicative (not monad) F. The role of this applicative is to allow subprograms to propagate their CSS needs to callers. Concretely, there would be a function style :: Css -> F () which acts akin to how tell acts in a writer monad. There would also be affordances to embed actions from your industrial monad into F. Then each module which has its own CSS exports its API wrapped F; doing this tracks the CSS requirements. There would be a function compileCss :: F a -> Css which builds the composite CSS style and does not execute any effectful operations embedded within F. Additionally, there would be a function execute :: F a -> IO a which executes the actions embedded in the F a value. Then main could make use of compileCss to emit the CSS, and make use of execute to separately run the program.
I admit this is somewhat awkward... wrapping all your existing code in F will be annoying at best. However, I do think it is at least correct, insofar as it tracks effects.
Perhaps the proper answer is to use an existing component-based web framework, which allows you define your component markup and styling in the same place? Some of them support emitting to static HTML.

Haskell error when using the isNothing function in Maybe

I am trying to use isNothing in my code in Haskell, and it is giving me the error
<interactive>:97:23: error:
• Variable not in scope: isNothing :: Maybe t -> Bool
• Perhaps you meant data constructor ‘Nothing’ (imported from Prelude)
The code line I have is as follows -
maybeMap f value = if isNothing (value) then value else Just (f (check value))
this works fine if I replace isNothing value with value == Nothing, so I am confused why the previous is not working.
First thing's first, the key phrase in the error message is:
Variable not in scope: isNothing
Which means that the compiler just isn't aware of anything named isNothing.
That immediately tells you that the code around your your use of isNothing doesn't matter. It's not a problem with types, or anything to do with the actual isNothing function you're trying to call, and there's no way you can change the code around isNothing to get this to work.
Variable not in scope almost always means one of three things:
You haven't imported the name you're trying to use
You have accidentally misspelled the name you're trying to use
You intended to define something with that name, but haven't done so yet
Changing any of the code surrounding your use of isNothing isn't going to change any of those 3 problems no matter which it is. Even looking at that code isn't going to tell you anything relevant; just closely look at the spelling of the name in the error message to confirm you haven't just made a typo, and if not you know you need to look elsewhere.
In this case it's #1. There are a bunch of useful functions that are in the Haskell Prelude which are automatically imported for you, so you're probably used to just using functions without importing them, but the "normal" case is that to use anything that's already defined you have to import it. isNothing isn't in the Prelude, so that means to use it you have to find out which module it is in and add an import declaration to make it available. (If that module is in a package that isn't already installed, you will also have to obtain the package; that's a question I'm not going to address here)
isNothing comes from the Data.Maybe module (in the base package, which is always installed as part of installing GHC, so no worries there). So you need to use:
import Data.Maybe
If you're working in a file you need to add that to the top of the file (just after the module header, but before you define any names yourself; all imports must come before any of your own code). If you're using the interpreter you can just enter the import as a command.
That will bring all of the names defined in Data.Maybe into scope. If you want more control, you can explicitly import only some of the names, like this:
import Data.Maybe ( isNothing, isJust, listToMaybe )
The function isNothing is not part of the standard prelude. Rather, it's distributed as part of the Data.Maybe module. To use isNothing, you'll need to explicitly import that module:
import Data.Maybe

Prism over maybe-existent list element

today on "adventures in functional programming with lenses" our hero attempts to define a prism over a list element that may or may not exist.
It's a bit tricky to explain, so to avoid the X, Y problem I'll give the actual use-case in all its glory.
I'm writing a Text editor in Haskell called Rasa, the whole idea is that it's extremely extensible, and that means most functionality is written as extensions. Since it's a core principle, extensions ALSO depend on other extensions, so I needed a way to store their state centrally such that all extensions depending on an extension could access its current 'extension state'. Of course the types of these states is not known to the core of the editor, so at the moment I'm storing a list of Dynamic values. When the extension stores the state it converts to a Dynamic, then it can be extracted later via a prism like so:
data Store = Store
{ _event :: [Event]
, _editor :: E.Editor
, _extState :: [Dynamic]
}
ext :: Typeable a => Traversal' Store a
ext = extState.traverse._Dynamic
So now ext is a polymorphic Traversal that essentially operates over only the Dynamics that 'match' the type in question (if you set to it it'll replace values of the same type, if you 'get' from it, it acts as a traversal over the Dynamics that match the type of the outbound value). If that seems like magic, it basically is...
BTW, I'd love to have exactly 1 copy of a given Extension's state object in the list at any time.
So getting and setting is actually working fine IFF there's already a value of the proper type in the list, my question is how can I make a version of this Traversal such that if a value of the proper type is in the list that it will replace it (and getting works as expected), but that will ADD a value to the list if the traversal is SET to and there's NO matching element in the list. I understand that Traversal's aren't supposed to change the number of elements that they're traversing, so perhaps this needs to be a prism or lens over the list itself?
I understand this is really confusing, so please ask clarifying questions :)
As for things I've taken a look at already, I was looking at prefixed and _Cons as possible ways to do this, but I'm just not quite sure how to wire it up. Maybe I'm barking up the wrong tree entirely.
I could perhaps add a default value to the end of the traversal somehow, but I don't want to require Monoid or Default so I can't conjure up elements from nowhere (and I only want to do it when SETTING).
I'm also open to discussions about whether this is actually the proper way to store this state at all, but it's the most elegant of solutions I've found so far (though I know typecasting at run time is sub-optimal). I've looked into the Vault type, but passing keys around didn't really work well when I tried it (and I imagine it has similar type-casting performance issues).
Cheers! Thanks for reading.
I think the list of extensions is not proper solution for you. I would be added something like _extState :: Map TypeRep Ext where data Ext = forall a. Ext a. Then I would be added the lens:
ext :: forall a . Typeable a => Lens' Store (Maybe a)
ext = _extState . at (typeRep (Proxy :: Proxy a)) . mapping coerce
where
coerce = iso (\(Ext x) -> unsafeCoerce x) Ext
This lens does like at. So you can simply get/set your extensions.
But there is one limitation, all extensions must be of different types.

Alpha conversion on a Haskell expression

Given a Haskell expression, I'd like to perform alpha conversion, ie. rename some of the non free variables.
I've started implementing my own function for this, which works on a haskell-src-exts Exp tree, however it turns out to be surprisingly nontrivial, so I can't help wondering - is there an established easy-to-use library solution for this kind of source conversion? Ideally, it should integrate with haskell-src-exts.
This is one of the problems where the "Scrap Your Boilerplate" style generic libraries shine!
The one I'm most familiar with is the uniplate package, but I don't actually have it installed at the moment, so I'll use the (very similar) functionality found in the lens package. The idea here is that it uses Data.Data.Data (which is the best qualified name ever) and related classes to perform generic operations in a polymorphic way.
Here's the simplest possible example:
alphaConvert :: Module -> Module
alphaConvert = template %~ changeName
changeName :: Name -> Name
changeName (Ident n) = Ident $ n ++ "_conv"
changeName n = n
The (%~) operator is from lens and just means to to apply the function changeName to everything selected by the generic traversal template. So what this does is find every alphanumeric identifier and append _conv to it. Running this program on its own source produces this:
module AlphaConv where
import Language.Haskell.Exts
import Control.Lens
import Control.Lens.Plated
import Data.Data.Lens
instance Plated_conv Module_conv
main_conv
= do ParseOk_conv md_conv <- parseFile_conv "AlphaConv.hs"
putStrLn_conv $ prettyPrint_conv md_conv
let md'_conv = alphaConvert_conv md_conv
putStrLn_conv $ prettyPrint_conv md'_conv
alphaConvert_conv :: Module_conv -> Module_conv
alphaConvert_conv = template_conv %~ changeName_conv
changeName_conv :: Name_conv -> Name_conv
changeName_conv (Ident_conv n_conv)
= Ident_conv $ n_conv ++ "_conv"
changeName_conv n_conv = n_conv
Not terribly useful since it doesn't distinguish between identifiers bound locally and those defined in an outside scope (such as being imported), but it demonstrates the basic idea.
lens may seem a bit intimidating (it has a lot more functionality than just this); you may find uniplate or another library more approachable.
The way you'd approach your actual problem would be a multi-part transformation that first selects the subexpressions you want to alpha-convert inside of, then uses a transformation on those to modify the names you want changed.

How to get the literal value of a TemplateHaskell named variable

If I have a Name in TemplateHaskell and want to find out the value of the variable that it names, provided that the variable is declared as a literal, can this be done?
var = "foo"
-- Can `contentsOf` be defined?
$((contentsOf . mkName $ "var") >>= guard . (== "foo"))
In theory, yes. In practice, no.
Finding out stuff about existing names is done using reify :: Name -> Q Info, and for a definition like that you would get back a VarI value, which includes a Maybe Dec field. This would seem to suggest that you might in some cases be able to get the syntax tree for the declaration of the variable, which would allow you to extract the literal, however current versions of GHC always returns Nothing in this field, so you're out of luck for a pure TH solution.
However, TH does allow arbitrary IO actions to be run, so you could potentially work around this by loading and parsing the module yourself using something like haskell-src-exts, however I suspect that would be more trouble than it's worth.

Resources