Prism over maybe-existent list element - haskell

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.

Related

How would implement a feature to save Monads with associated names on disk?

So I have a simple parser library (it doesn't parse strings but whatever) and I need the parsers to have potential names etc.
So, for example, the user might take the parsers
space >> space
and then apply the name twoSpaces to this parser. This would then be saved to disk (not sure how exactly) to be later reloaded when the application is rerun.
So my question is:
Should this functionality be wrapped say in this:
type Name = String
newtype NamedParser a = NamedParser (Parser a) Name
Or should my definition of Parser be changed from:
newtype Parser a = Parser { parse :: a -> FilterResult a }
to:
newtype Parser a = Parser { parse :: a -> FilterResult a
, name :: Name }
My intuition worries here about both speed of the program and implementation (sometimes I won't want to name parsers etc).
An extension of this question is whether I can then allow the user to save these new parsers in data files for between runtimes. This way the user can build a library of tools that can load in.
I can imagine a good way of doing this being an appropriate Writer/Parser duo that saves this stuff to files, with the resulting Haskell code then added to my libraries. Is there a convention for such things or is that what I should go for. Is TemplateHaskell a better alternative for this??
Finally, how would I add and delete these new metaprogrammed functions​ efficiently - is there a convention for that?

How to introspect an Haskell file to get the types of its definitions

I have many files that must be processed automatically. Each file holds the response of one student to an exercise which asks the student to give definitions for some functions given a type for each function.
My idea is to have an Haskell script that loads each student file, and verifies if each function has the expected type.
A constraint is that the student files are not defined as modules.
How can I do this?
My best alternative so far is to spawn a GHCi process that will read stdin from a "test file" with GHCi commands, for example:
:load student1.hs
:t g
... and so on ...
then parse the returned output from GHCi to find the types of the functions in the student file.
Is there another clean way to load an arbitrary Haskell file and introspect its code?
Thanks
Haskell does not save type information at runtime. In Haskell, types are used for pre-runtime type checking at the static analysis phase and are later erased. You can read more about Haskell's type system here.
Is there a reason you want to know the type of a function at runtime? maybe we can help with the problem itself :)
Edit based on your 2nd edit:
I don't have a good solution for you, but here is one idea that might work:
Run a script that for each student module will:
Take the name of the module and produce a file Test.hs:
module Test where
import [module-name]
test :: a -> b -> [(b,a)]
test = g
run ghc -fno-code Test.hs
check the output does not contain type errors
write results into a log file
I think if you have a dynamically determined number of .hs files, which you need to load, parse and introspect, you could/should use the GHC API instead.
See for example:
Using GHC API to compile Haskell sources to CORE and CORE to binary
https://mail.haskell.org/pipermail/haskell-cafe/2009-April/060705.html
These might not be something you can use directly — and I haven't done anything like this myself so far either — but these should get you started.
See also:
https://wiki.haskell.org/GHC/As_a_library
https://hackage.haskell.org/package/hint
The closest Haskell feature to that is Data.Typeable.typeOf. Here's a GHCi session:
> import Data.Typeable
> typeOf (undefined :: Int -> Char)
Int -> Char
> typeOf (undefined :: Int -> [Char])
Int -> [Char]
> typeOf (undefined :: Int -> Maybe [Char])
Int -> Maybe [Char]
> :t typeOf
typeOf :: Typeable a => a -> TypeRep
Under the hood, the Typeable a constraint forces Haskell to retain some type tags until runtime, so that they can be retrieved by typeOf. Normally, no such tags exist at runtime. The TypeRep type above is the type for such tags.
That being said, having such information is almost never needed in Haskell. If you are using typeOf to implement something, you are likely doing it wrong.
If you are using that to defer type checks to run time, when they could have been performed at compile time, e.g. using a Dynamic-like type for everything, then you are definitely doing it wrong.
If the function is supposed to be exported with a specific name, I think probably the easiest way would be to just write a test script that calls the functions and checks they return the right results. If the test script doesn't compile, the student's submission is incorrect.
The alternative is to use either the GHC API (kinda hard), or play with Template Haskell (simpler, but still not that simple).
Yet another possibility is to load the student's code into GHCi and use the :browse command to dump out everything that's exported. You can then grep for the term you're interested in. That should be quite easy to automate.
There's a catch, however: foo :: x -> x and foo :: a -> a are the same type, even though textually they don't match at all. You might contemplate trying to normalise the variable names, but it's worse: foo :: Int -> Int and foo :: Num x => x -> x don't look remotely the same, yet one type is an instance of the other.
...which I guess means I'm saying that my answer is bad? :-(

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.

HASKELL - Change Type

I need to create a function f:: Log->[String] that does that (((o, i ,d),s) = [(o, i ,d)]
type Log = (Plate, [String])
type Plate = (Pin, Pin, Pin)
type Pin = (Char, Int)
If you're on a page like this, click "Source" on the fir right side, next to the function that you're interested in.
If you need to look up a function, Hayoo! and Hoogle will link you to documentation pages like the one above.
An important thing to note, though is that show doesn't have one definition. show is a function defined for all data types in the Show (with a capital "S") typeclass. So for example, here is the full source for the Show typeclass. Show is defined within the typeclass as just show :: a -> String. But if you search for "instance Show Bool" or "instance Show Int", you'll find specific definitions.
For the second part of your question, the easiest way to get a show function for a new type is to simply write deriving (Show) below it. For example,
data Foo = Foo Int Int
deriving (Show)
Now I can use show on data with type Foo.
g :: Log -> [String]
g (plate, _) = [show plate]
Use hoogle to find this sort of information.
Example: http://www.haskell.org/hoogle/?hoogle=show
Once you've found the function you'd like in the list, click and there you'll find a Source link on the right hand side of the page.
NB this is an answer to the original question:
Where can I see the codes of the predefined functions in haskell ?? Mainly the function SHOW?
It's true that you can use Hoogle to search for functions defined in the Prelude (and other modules), but the source code itself is located at Hackage.
Hackage is a database of Haskell packages. You can download new packages from it, and also view the Haddock documentation for every package in the database.
This is the Haddock page for the standard Prelude. It documents the type classes, data types, types, and top-level functions exported by the Prelude module. To the right of each definition header is a link that says "Source". You can click this to be taken to an online copy of the source code for the module you're viewing.
On preview, you're now asking a different question entirely, and on preview again in fact the original question has been edited out of this post.
Your new question is unclear, but this solution will work to produce the output in your example.
> [fst ((('O',0),('I',0),('D',1)),"O->D")]
[(('O',0),('I',0),('D',1))]
I think you're using list notation instead of double quotes to identify Strings, by the way, so I fixed that around 0->D above. So you might also try this instead.
> show (fst ((('O',0),('I',0),('D',1)),"O->D"))
"(('O',0),('I',0),('D',1))"
This works because you have only defined type synonyms (by using type in your declarations instead of data) on data structures which already have Show instances.

Simple Haskell Instance Question

I'm trying different data structures for implementing Prim's algorithm. So I made a class to abstract what I want to do:
class VertexContainer a where
contains :: a -> Vertex -> Bool
insert :: a -> WeightedEdge -> a
numVertices :: a -> Int
Now I want to use a heap (from Data.Heap) as my vertex container. But I can't for the life of me figure out the syntax. As you can see from the insert declaration, the container can only hold WeightedEdges, which are a data type. So I tried:
instance VertexContainer (Heap MinPolicy WeightedEdge) where
contains _ _ = True
It tells me it's an illegal type synonym. I've tried various other permutations, and none of them seem to work. Can anyone help me?
If you read the entire error message you'll find that it tells you how to be able to use a type synonym in an instance declaration, namely by using the language extension TypeSynonymInstances. E.g., you can pass -XTypeSynonymInstances on the command line.
I got it working by wrapping this into a newtype. Considered ugly. I guess you have to wait for one of the Haskell gurus to answer this.

Resources