Haskell Haddock latex equation in comments - haskell

I'd like to use latex notation for equations in my source code.
For example, I would write the following comment in some haskell source file Equations.hs:
-- | $v = \frac{dx}{dt}$
In the doc directory, this gets rendered by haddock in Equations.tex as:
{\char '44}v = frac{\char '173}dx{\char '175}{\char '173}dt{\char '175}{\char '44}
I found this function in the source for Haddock's latex backend that replaces many characters that are used in latex formatting:
latexMunge :: Char -> String -> String
...
latexMunge '$' s = "{\\char '44}" ++ s
Is there any existing functionality that allows me to bypass this and insert latex equations in comments?

No. The main reason why this (and similar features) don't exist is that it's unclear what to do with the markup in the other backends, be it HTML one, Hoogle one or whatever else someone might be using. This is fairly commonly requested but there is no common agreement and more importantly, no patches.
Technically we don't support the LaTeX backend, it's kept around compiling so that the Haskell Report can be produced. If you or someone else wants to give it some new life (and features) then we'll happily accept patches.
tl;dr: no can do. I know people simply pre-render LaTeX and insert the resulting images in with the image syntax.

Related

Link two functions without a space between them

I am writing documentation for a library using haddock, and, for reasons that are not really necessary to explain, I need to include a little code block in my documentation that looks like:
z(<>)
Importantly there can be no space between z and (<>). It may be a bit esoteric but
z (<>)
would make my documentation incorrect, even if it is more stylistically correct.
Now I believe that hyperlinks to both z and (<>) would be helpful. Neither has a very informative name, so a link that helps people remember their definitions and purpose is nice.
So my code without the hyperlinks looks like:
#z(<>)#
And to add hyperlinks I just use single quotes:
#'z''(<>)'#
Except that doesn't work, haddock sees 'z'' and thinks that I mean to link z' (a function that does exist in my module), and then just leaves the rest alone. The rendered output looks like
z'(<>)'
Now as an experiment I deleted the definition of z', however the only difference this makes is that the link to z' goes away. The raw text remains the same. The next thing I tried was ditching #s altogether and did
'z''(<>)'
Which also created a hyperlink to z' and left the rest untouched, the same problem as earlier except now nothing is in a code block.
How can I make a code block that links two functions without a space between?
You can separate the two functions into different code blocks. If there is no space between the code blocks, it will appear no different than a single code block. So
#'z'##'(<>)'#
will render as desired.
You can also do it in one code block by moving the 's inside of the parentheses to only surround <>.
#'z'('<>')#
This will render slightly differently with the parentheses not being part of any hyperlink, however this may be desired.
Here is an alternative solution to add to the answer you already provided:
You can mix and match ' and `. These two will also be rendered correctly by haddock:
-- | #`z`'(<>)'#
-- | #'z'`(<>)`#
At the same time I've tried your solution #'z'##'(<>)'# and for some reason it did not render for me properly, but with haddock you never know.
Here are all of the ones that I've tried:
-- * #'z'##'(<>)'#
-- * #'z'('<>')#
-- * #'z'`(<>)`#
-- * #`z`'(<>)'#
With corresponding result:

Use Alex macros from another file

Is there any way to have an Alex macro defined in one source file and used in other source files? In my case, I have definitions for $LowerCaseLetter and $UpperCaseLetter (these are all letters except e and O, since they have special roles in my code). How can I refer to these macros from other .x files?
Disproving something exists is always harder than finding something that does exist, but I think the info below does show that Alex can only get macro definitions from the .x file it is reading (other than predefinied stuff like $white), and not via includes from other files....
You can get the sourcecode for Alex by doing the following:
> cabal unpack alex
> cd alex-3.1.3
In src/Main.hs, predefined macros are first set in variables called initSetEnv (charset macros $white, $printable, and "."), and initREEnv (regexp macros, there are none). This gets passed into runP, in src/ParseMonad.hs, which is used to hold the current parsing state, including all defined macros. The initial state is set using the values passed in, but macros can be added using a function called newSMac (or newRMac for regular expression macros).
Since this seems to be the only way that macros can be set, it is then only a matter of some grep bookkeeping to verify the only ways that macros can be added is through an actual macro definition in the source .x file. Unsurprisingly, Alex recursively uses its own .x/.y files for .x source file parsing (src/parser.y, src/Scan.x). It is a couple of levels of indirection away, but you can verify that the only way newSMac can be called is through the src/Scan.x macro
#smac = \$ #id | \$ \{ #id \}
<0> #smac #ws? \= { smacdef }
Other than some obvious predefined stuff, I don't believe reuse in lexers is all that typical anyway, because at the token level things are usually pretty simple (often simple tokens like SPACE, WORD, NUMBER, and a few operators, symbols and parens are all that are needed). The complexity comes at the parsing stage, although for technical reasons, parser-includes aren't that common either (see scannerless parsing for a newer technology that does allow reuse through nesting, like javascript embedded in html.... The tools for scannerless parsing are still pretty primitive though).

Does any literate programming environment support on the fly results?

I am currently writing lots of small reports. Most of them are just value dumps with some graphs and illustrative comments.
Is there a literate programming environment that let's me write my reports in an easy format (preferably markdown/latex and haskell) and then converts to some output format (preferably pdf) that contains results of the calculations done in the original file?
I know that Haskell supports literate programming but I don't think that the output (and possibly whole images) can be captured.
The lhs2TeX preprocessor supports evaluating Haskell expressions via GHCi. Here's a minimal example:
\documentclass{article}
%include polycode.fmt
%options ghci
\begin{document}
Running
> fmap (+1) [1..10]
yields \eval{fmap (+1) [1..10]}.
\end{document}
This will produce output which contains the list [2,3,4,5,6,7,8,9,10,11] in the place where the \eval command is in the input.
You can reference definitions from the current file. I.e., the \eval function works by loading the current file into ghci and then evaluating the expression in that context.
There's also \perform which does the same as \eval, but the output will not be seen as a piece of Haskell code, but rather as a piece of LaTeX code. So you can write Haskell functions that generate parts of your output document.
That being said, there are lots of things that could be improved about this functionality in lhs2TeX, and the implementation is quite a hack.
EDIT: Concluding from the comments, the goal is to include images generated by the Chart library. Here is a proof-of-concept document that shows how to achieve this:
\documentclass{article}
\usepackage{graphicx}
%include polycode.fmt
%options ghci
%if style == newcode
(Stuff here will not be typeset by LaTeX, but seen by Haskell.)
> import Data.Accessor
> import Graphics.Rendering.Chart
>
> renderAndInclude :: Renderable a -> FilePath -> IO ()
> renderAndInclude r filename = do
> renderableToPDFFile r 200 200 filename
> putStrLn $ "\\includegraphics{" ++ filename ++ "}"
%endif
%format ^= = "\mathbin{{}^\wedge\!\!=}"
\begin{document}
The image description
> image :: Renderable ()
> image = toRenderable
> $ layout1_title ^= "Test"
> $ layout1_plots ^= [ Left (toPlot plot) ]
> $ defaultLayout1
> where
> plot = plot_lines_values ^= [[ (x, sin x) | x <- [0, 0.01 .. 10 :: Double] ]]
> $ defaultPlotLines
yields the following output:
\perform{renderAndInclude image "image.pdf"}.
\end{document}
The central helper function you have to write is something like renderAndInclude above that performs the actual rendering, writes the result to a file, and produces a LaTeX \includegraphics command that reads back the file.
If you don't absolutely have to have Haskell, you can get the rest with Sweave and R. You basically write a LaTeX document, with embedded R code. You can choose to include either the code, the result (including plots), or both in your final PDF output. Knitr is a more recent extension (or simplification?) of Sweave.
If you want to use diagrams instead of chart, then diagrams-builder as described in this blog post is your friend. Works with markdown and LaTeX alike.
You can try http://code.google.com/p/nano-lp/, it supports Markdown/Multimarkdown and other lightweight markups (but also OpenOffice) and it's easy to include several files into one. With OpenOffice, you can export your resulting file to PDF, for example. Also Asciidoc is supported and TeX/LaTeX, so you can use them to produce PDF too
Sorry for being (very) late to the party. The answer comes only as a reference for future visitors to this question.
Org-mode does provide a nice literate programming environment. Albeit a universe in itself, it's well worth looking into! Some more information about the way it handles code can be found in these links:
Org-mode manual, chapter 14
Babel: Active code in Org-mode
Tutorial for R
There is ofc also support for Haskell, else this comment would be superfluous. While the format isn't Markdown, Org-mode has a very simple way of marking up things.

Embedding a domain specific language in an OCaml toplevel -- to Camlp4 or not?

I have some code that includes a menhir-based parser for a domain specific language (a logic). For the sake of my sanity while debugging, it would be great to be able to type instances of this language (formulas) directly in the toplevel like so:
# f = << P(x,y) & x!=y >>
Is campl4/5 my only option? If yes, I find the documentation rather intimidating. Is there an example/tutorial that is close-enough to my use case and that I could conceivably adapt? (For instance, syntax extensions that introduce new keywords do not seem relevant). Thanks!
If you're willing to call a function to do the parsing, you can use ocamlmktop to include your parser into the top level. Then you can install printers for your types using #install_printer. The sessions might look like this then:
# let x = parse ()
<< type your expression here >>
# x : type = <<formatted version>>
I have used specialed printers, and they definitely help a lot with complicated types. I've never gotten around to using ocamlmktop. I always just load in my code with #load and #use.
This is a lot easier than mastering camlp4/5 (IMHO). But maybe it's a bit too crude.
Yes, you can use camlp4 and it will work reasonably well (including in the toplevel), but no, it's not well-documented, and you will have to cope with that.
For an example that is close to your use-case, see the Lambda calculus quotation example of the Camlp4 wiki.
For the toplevel, it will work easily. You can dynamically load "camlp4o.cmo" then your syntactic extension in the toplevel, or use findlib which handles that: from the toplevel, #use "topfind";;, then #camlp4o;;, then #require "myfoo.syntax";; where myfoo.syntax is the name of the findlib package you've created to deploy your extension.

LHS and Markdown: Codeblocks

I happen to really like Markdown (probably because of SO) and I like programming in Haskell. I have recently discovered Literate Haskell (LHS) and I want to use Markdown and LHS together. Let me give you this dumb example:
Crazy Literate Haskell
======================
This is an example of some literate Haskell Code:
> module Main where
Look at that IO Monad work:
> main = return 2 >>= print
Wasn't that cool?
That is an example of a literate haskell file written to be parsed by Markdown later. However, I want the code to actually appear in html code blocks and without the > before them. Therefore I cannot merely indent all of the code lines by four because that would produce the markdown that you see above. Basically, I want the html to come out like this:
<h1>Crazy Literate Haskell</h1>
<p>This is an example of some literate Haskell Code:</p>
<pre><code>module Main where
</code></pre>
<p>Look at that IO Monad work:</p>
<pre><code>main = return 2 >>= print
</code></pre>
<p>Wasn't that cool?</p>
The thing to notice is that it has no > symbols. How would I do that?
Use Pandoc. It has a markdown+lhs mode for using markdown in literal Haskell files, and if you don't like the html it produces, there is an api for modifying the document structure.
Install it with
cabal install pandoc

Resources