Does any literate programming environment support on the fly results? - haskell

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.

Related

Haskell: Parse error: module header, import declaration or top-level declaration expected

I am saving some commands in a Haskell script in a .hs file while working thru a Haskell textbook. Here's a small example.
fst (1,2)
snd (1,2)
When I run these commands from the prelude in GHCi, they work fine. When I try to compile the .hs file with these two lines, I get the following:
ch4_test.hs:2:1: error:
Parse error: module header, import declaration
or top-level declaration expected.
|
2 | fst (1,2)
| ^^^^^^^^^
Failed, no modules loaded.
I've googled this error and can't find any explanation what I'm doing wrong.
From a newbie to future newbies: The interactive environment ghci would lead you to believe that you can punch some expressions into an .hs file and run the thing (in a similar fashion to languages like swift and ruby). This is not the case.
Haskell needs an entrypoint called main. Quoting:
Here is a simple program to read and then print a character:
main :: IO ()
main = do c <- getChar
putChar c
The use of the name main is important: main is defined to be the entry point of a Haskell program (similar to the main function in C), and must have an IO type, usually IO ()
Source: https://www.haskell.org/tutorial/io.html
You can't just put any expression in a hs file.
As the error message says, you need a declaration here. For example:
main =
print (fst (1,2)) >>
print (snd (1,2))
I am getting this error but the cause appears to be completely different from anything posted here. And the error message is not at all helpful.
Using Cabal version 3.6.2.0 with GHCI 8.10.7 on MacOS High Sierra (10.13)
I'm working from this page: https://www.tutorialspoint.com/haskell/haskell_modules.htm
specifically the "custom modules" section. There you can see the code I copied and pasted.
Besides the tutorial not mentioning I needed to add "other-modules: Custom" to myfirstapp.cabal, and besides the fact that the sample Custom.hs file includes "if x 'rem' 2 == 0" rather than "if x rem 2 == 0", here is the problem:
Indentation matters!
This line (inside the quotes) does NOT work "if x rem 2 == 0".
This line DOES work " if x rem 2 == 0"!
Indenting by one space is the difference between success and failure.
I'm totally new to Haskell. I've programmed extensively in PHP, Javascript, and Applescript, and dabbled in a dozen others, and this is the first time I've seen white space matter. I assume this is commonly known amongst Haskell veterans, but it would certainly be nice if that was included prominently in the documentation.

Haskell Haddock latex equation in comments

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.

how to plot a graph using haskell graphViz

I'm planning to draw a graph using Haskell graphViz. I'm new to haskell, so this is quite difficult for me. Can someone show me a simple example ? I need a very simple example actually, so that I can understand it and use it in the scenario I'm working on
I get the above error on trying to install chart-cairo. I saw some examples on the internet and all of them requires chart-cairo. any idea how to resolve it ?
*EDITED"
The output that I get after executing the code given by https://stackoverflow.com/users/2827654/jamshidh
(This addresses your original question, described in the title, and doesn't go into the problems installing chart-cairo or chart, etc, which really should be spun out into different questions)....
The graphviz package includes some example graphs in module Data.Graph.Inductive.Example that can be used to get you up and running. You can see the list of included graphs at http://hackage.haskell.org/package/fgl-5.3/docs/Data-Graph-Inductive-Example.html.... I will use one called clr479.
Once you have a graph, you can convert it to an internal structure representing the dot format using graphToDot. Note that you will need to supply some parameters, which are described in http://hackage.haskell.org/package/graphviz-2999.11.0.0/docs/Data-GraphViz.html. Just to get up and running, I will use the supplied nonClusteredParams.
let graphInDotFormat = graphToDot nonClusteredParams clr479
Then, you will need to convert this to text suitable for input to the dot program. You can do this with renderDot . toDot
let outputText = renderDot $ toDot graphInDotFormat
and, as usual, you need to convert text to string to use putStrLn (don't just use show, as it will include quotes and escape sequences, which dot will not understand)
putStrLn $ unpack outputText
Putting this all together, the final program createDotFile.hs would be
import Data.Text.Lazy
import Data.GraphViz
import Data.Graph.Inductive.Example
import Data.GraphViz.Printing
main = putStrLn $ unpack $ renderDot $ toDot $ graphToDot nonClusteredParams clr479
Compile using ghc createDotFile.hs (remember to cabal install the required packages, as well as graphviz itself if you want to do anything with the output). On the commandline, you can now pipe the output of this program to dot, which will convert this to a usual format.... For instance, here I convert to svg
./createDotFile | dot -Tsvg > graph.svg
which on my linux box can be viewed by typing
eog graph.svg
Edit-
To clarify, the output of the haskell program needs to be provided as an input to GraphViz. The msi file to install graphviz on windows here http://www.graphviz.org/Download_windows.php.

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

How do I rotate a JPEG image by 45° and save it back to disk in Haskell?

How do I rotate a JPEG image by 45° and save it back to disk?
As far as I know, there is no good image manipulation library for Haskell yet.
Better way
You can use hsmagick (bindings to libmagick) to manipulate images.
See TomMD's answer for an example.
Easy way
But if you want to do it from Haskell, this can do the trick (assuming that ImageMagick is available):
import System.Cmd (system)
import System.Environment (getArgs)
main = do
(original:rotated:_) <- getArgs
system $ "convert -rotate \"-45\" \"" ++ original ++ "\" \"" ++ rotated ++ "\""
Usage:
runghc rotate.hs original.jpg rotated45.jpg
Hard way
Or you can choose the hard way, and implement rotation algorithm yourself. To read and write almost all image formats in Haskell, you can use Codec.Image.DevIL library. If you do it, it would be kind of you to put this code on Hackage.
The GD library lets you do this, but the Haskell bindings ( http://hackage.haskell.org/package/gd ) don't include the appropriate function at the moment. One also could either make a feature request to the maintainer, or simply patch it and send it upstream. The Graphics.GD.Internal module (not exported) in fact already has a commented out binding to the appropriate function ( http://hackage.haskell.org/packages/archive/gd/3000.5.0/doc/html/src/Graphics-GD-Internal.html ), so it should be very simple, I imagine, to finish the job (and I'm sure, the work will be appreciated).
Look around on Hackage. I know Tim started working on bindings to libmagick, which wasn't enough to stop me from dropping down to generating script-fu for GIMP when I needed image manipulation, but it's enough for you if you're just doing simple things like rotation:
liftM (rotateImage 45) (readImage file) >>= writeImage file2
I see Cale also has an ImLib that appears more feature complete:
loadImageImmediately file >>= contextSetImage >>
createRotatedImage 45 >>= contextSetImage >> saveImage file2
As I said, look around and let us know!

Resources