LHS and Markdown: Codeblocks - haskell

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

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.

GHC: insert compilation date

I thought there would already be a question about this, but I can't find one.
I want my program to print out the date it was compiled on. What's the easiest way to set that up?
I can think of several possibilities, but none of them are what you'd call "easy". Ideally I'd like to be able to just do ghc --make Foo and have Foo print out the compilation date each time I run it.
Various non-easy possibilities that spring to mind:
Learn Template Haskell. Figure out how to use Data.Time to fetch today's date. Find a way how to transform that into a string. (Now my program requires TH in order to work. I also need to convince it to recompile that module every time, otherwise I get the compilation date for that module [which never changes] rather than the whole program.)
Write a shell script that generates a tiny Haskell module containing the system date. (Now I have to use that shell script rather than compile my program directly. Also, shell scripting on Windows leaves much to be desired!)
Sit down and write some Haskell code which generates a tiny Haskell module containing the date. (More portable than previous idea - but still requires extra build steps or the date printed will be incorrect.)
There might be some way to do this through Cabal - but do I really want to package up this little program just to get a date facility?
Does anybody have any simpler suggestions?
Using Template Haskell for this is relatively simple.
You just need to:
Run IO action within Template Haskell monad:
runIO :: IO a -> Exp a
Then create a string literal with:
stringE :: String -> ExpQ
Put a whole expression within a quasiquote.
$( ... )
This program will print time of its compilation:
{-# LANGUAGE TemplateHaskell #-}
import Language.Haskell.TH
import Data.Time
main = print $(stringE =<< runIO (show `fmap` Data.Time.getCurrentTime))
You may put the relevant fragment into a module that imports all other modules to make sure it is recompiled.
Or take current revision information from your versioning system. See: TemplateHaskell and IO
The preprocessor helpfully defines __DATE__ and __TIME__ macros (just like in C), so this works:
{-# LANGUAGE CPP #-}
main = putStrLn (__DATE__ ++ " " ++ __TIME__)
This is probably simpler than Michal's suggestion of Template Haskell, but doesn't let you choose the format of the date.

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.

Is it possible to do code generation in Coffeescript?

Say I have some Coffeescript (with Underscore.js mixed in) like this:
someData =
hello: 'haha'
_(3).times (index) ->
someData["key-#{index}"] = index
The value of someData will then be:
hello: 'haha'
key-0: 0
key-1: 1
key-2: 2
It would be nice if Coffeescript had some syntactic sugar that allows me to write something like this:
someData =
hello: 'haha'
<%
_(3).times (index) ->
%>
key-#{index}: index
which would produce someData whose value would be identical to the original.
Is there such facility in Coffeescript?
Short answer: No.
Longer answer: This kind of syntax would go beyond CoffeeScript's intent of being a simple language that's ~1:1 with JavaScript. However, you could use another templating language on top of CoffeeScript. In fact, with Rails 3.1, it's pretty straightforward to have a .coffee.erb file where Ruby code can be used to generate CoffeeScript code, much like your hypothetical example.
To complement Trevor's answer: code generation (a'la Lisp) is indeed powerful, but you can also build structures with some basic abstractions. For your example (it uses a couple of functions from this underscore mixin):
data = _(
hello: 'haha'
).merge(_([0..2]).mash (x) -> ["key-" + x, x])
Short answer: Yes, sort of.
Slightly less short answer:
You can do what the OP is after in fine style, since coffeescript is written in coffeescript (which is written in coffeescript ;). Sth like ERB templates are probably a better choice if your use-case is very simple, but there's nothing like programmatically manipulating AST structures for really powerful & reusable code-generation.
In this regard, Coffeescript shows something almost kinda-sorta halfway like http://en.wikipedia.org/wiki/Homoiconicity (the joy of lisps) but not really.
Here's an example:
http://blog.davidpadbury.com/2010/12/09/making-macros-in-coffeescript/
nostalgic musing follows
"javascript" was inspired by http://en.wikipedia.org/wiki/Scheme_(programming_language) ... before it was called javascript ... and so coffeescript is kinda bringing JS back to its roots, eliding the marketing jibberish in its syntax, which was shoehorned in because of ill-conceived micromanagement on the part of Sun & Netscape executives.

Resources