$$e^{ix} =\text{cos}(x) + i \text{sin} (x)$$

Inline formulae get correctly aligned to match the baseline of the surrounding text.

## Implementation
Theorem environments are written using [pandoc](http://pandoc.org)s support for block environments:
~~~ {.markdown}
$\text{tan}(\phi) = \frac{\text{sin}(\phi)}{\text{cos}(\phi)}$

Formulae are rendered with $\text{\LaTeX}$ and included as [SVG](https://en.wikipedia.org/wiki/SVG).

~~~
Combined with a smattering of CSS this works nicely.
$\text{\LaTeX}$ support is, however, lacking as I opted not to patch pandoc ([math.kleen.org](https://math.kleen.org) did).
### `Math.hs`
The actual compilation happens in a new module I named `Math.hs`. We´ll start there.
For your reading pleasure I added some comments to the reproduction below.
~~~ {.haskell}
module Math
( compileMath
) where
import System.IO (stdout, stderr, hPutStrLn, writeFile, readFile)
import System.IO.Temp (withSystemTempDirectory)
import System.Process (callProcess, readProcessWithExitCode)
import System.Directory (copyFile, getCurrentDirectory, setCurrentDirectory)
import System.FilePath (takeFileName, FilePath(..), ())
import System.Exit (ExitCode(..))
import Control.Monad (when)
import Control.Exception (bracket, throwIO)
import Data.Maybe (fromMaybe, listToMaybe)
import Control.Monad.Writer.Strict (WriterT(..), execWriterT, tell)
import Control.Monad.Trans (liftIO)
import Control.DeepSeq (($!!))
import Text.Regex.TDFA ((=~))
-- We built a monoid instance for `ExitCode` so we can easily collect failure using a `MonadWriter`
instance Monoid ExitCode where
mempty = ExitSuccess
(ExitFailure a) `mappend` _ = ExitFailure a
ExitSuccess `mappend` x@(ExitFailure _) = x
ExitSuccess `mappend` ExitSuccess = ExitSuccess
compileMath :: String -> IO (String, String)
compileMath = withSystemTempDirectory "math" . compileMath' -- Create a temporary directory, run `compileMath'`, and make sure the directory get's deleted
compileMath' :: String -> FilePath -> IO (String, String)
compileMath' input tmpDir = do
mapM_ (copyToTmp . ("tex" )) [ "preamble.tex"
, "preview.dtx"
, "preview.ins"
]
(exitCode, out, err) <- withCurrentDirectory tmpDir $ execWriterT $ do -- Collect stdout, stderr, and exitCode of all subprocesses (stdout and stderr simply get appended to one another)
run "latex" [ "-interaction=batchmode"
, "preview.ins"
] ""
liftIO $ writeFile (tmpDir "image.tex") input
run "latex" [ "-interaction=batchmode"
, "image.tex"
] ""
run "dvisvgm" [ "--exact"
, "--no-fonts"
, tmpDir "image.dvi"
] ""
when (exitCode /= ExitSuccess) $ do -- Fail with maximum noise if any of the latex passes fail -- otherwise be silent
hPutStrLn stdout out
hPutStrLn stderr err
throwIO exitCode
(\x -> return $!! (x, extractAlignment err)) =<< (readFile $ tmpDir "image.svg") -- Note the call to `($!!)` -- since we'll be deleting `tmpDir` we need to make sure the entire generated output resides in memory before we leave this block
where
copyToTmp fp = copyFile fp (tmpDir takeFileName fp)
run :: String -> [String] -> String -> WriterT (ExitCode, String, String) IO ()
run bin args stdin = tell =<< liftIO (readProcessWithExitCode bin args stdin)
withCurrentDirectory :: FilePath -- ^ Directory to execute in
-> IO a -- ^ Action to be executed
-> IO a
-- ^ This is provided in newer versions of temporary
withCurrentDirectory dir action =
bracket getCurrentDirectory setCurrentDirectory $ \ _ -> do
setCurrentDirectory dir
action
extractAlignment :: String -> String
extractAlignment = fromMaybe "0pt" . extract . (=~ "depth=([^\\s]+)") -- One of the few places where regular expressions really prove usefull
where
extract :: (String, String, String, [String]) -> Maybe String
extract (_, _, _, xs) = listToMaybe xs
~~~
### `Site.hs`
The more trick part proved to be integration into the framework as provided by [Hakyll](http://jaspervdj.be/hakyll/).
~~~ {.haskell}
…
import qualified Crypto.Hash.SHA256 as SHA256 (hash)
import qualified Data.ByteString.Char8 as CBS
import Data.Hex (hex)
import Data.Char (toLower)
import Math (compileMath)
import Text.Printf (printf)
main :: IO ()
main = hakyllWith config $ do
…
math <- getMath "posts/*" mathTranslation'
forM_ math $ \(_, mathStr) -> create [mathTranslation' mathStr] $ do
route idRoute
compile $ do
item <- makeItem mathStr
>>= loadAndApplyTemplate "templates/math.tex" defaultContext
>>= withItemBody (unsafeCompiler . compileMath) -- unsafeCompiler :: IO a -> Compiler a
saveSnapshot "alignment" $ fmap snd item
return $ fmap fst item
match "posts/*" $ do
route $ setExtension ".html"
compile $ do
getResourceBody >>= saveSnapshot "content"
pandocCompilerWithTransformM defaultHakyllReaderOptions defaultHakyllWriterOptions mathTransform -- pandocCompilerWithTransformM :: ReaderOptions -> WriterOptions -> (Pandoc -> Compiler Pandoc) -> Item String
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
…
…
mathTranslation' :: String -> Identifier
-- ^ This generates the filename for a svg file given the TeX-source
mathTranslation' = fromCapture "math/*.svg" . map toLower . CBS.unpack . hex . SHA256.hash . CBS.pack
getMath :: Pattern -> (String -> Identifier) -> Rules [([Identifier], String)]
-- ^ We scrape all posts for math, calls `readPandoc'`
getMath pattern makeId = do
ids <- getMatches pattern
mathStrs <- concat `liftM` mapM (\id -> map ((,) [id]) `liftM` getMath' (toFilePath' id)) ids
return $ mergeGroups $ groupBy ((==) `on` snd) $ mathStrs
where
getMath' :: FilePath -> Rules [String]
getMath' path = preprocess (query extractMath `liftM` readPandoc' path)
extractMath :: Inline -> [String]
extractMath (Math _ str) = [str]
extractMath _ = []
mergeGroups :: [[([Identifier], String)]] -> [([Identifier], String)]
mergeGroups = map mergeGroups' . filter (not . null)
mergeGroups' :: [([Identifier], String)] -> ([Identifier], String)
mergeGroups' xs@((_, str):_) = (concatMap fst xs, str)
readPandoc' :: FilePath -> IO Pandoc
-- ^ This is copied, almost verbatim, from Hakyll source -- Does what it says on the tin
readPandoc' path = readFile path >>= either fail return . result'
where
result' str = case result str of
Left (ParseFailure err) -> Left $
"parse failed: " ++ err
Left (ParsecError _ err) -> Left $
"parse failed: " ++ show err
Right item' -> Right item'
result str = reader defaultHakyllReaderOptions (fileType path) str
reader ro t = case t of
DocBook -> readDocBook ro
Html -> readHtml ro
LaTeX -> readLaTeX ro
LiterateHaskell t' -> reader (addExt ro Ext_literate_haskell) t'
Markdown -> readMarkdown ro
MediaWiki -> readMediaWiki ro
OrgMode -> readOrg ro
Rst -> readRST ro
Textile -> readTextile ro
_ -> error $
"I don't know how to read a file of " ++
"the type " ++ show t ++ " for: " ++ path
addExt ro e = ro {readerExtensions = Set.insert e $ readerExtensions ro}
mathTransform :: Pandoc -> Compiler Pandoc
-- ^ We replace math by raw html includes of the respective svg files here
mathTransform = walkM mathTransform'
where
mathTransform' :: Inline -> Compiler Inline
mathTransform' (Math mathType tex) = do
alignment <- loadSnapshotBody texId "alignment"
let
html = printf ""
(toFilePath texId) (alignment :: String) tex
return $ Span ("", [classOf mathType], []) [RawInline (Format "html") html]
where
texId = mathTranslation' tex
classOf DisplayMath = "display-math"
classOf InlineMath = "inline-math"
mathTransform' x = return x
…
~~~
]]>
$$e^{ix} =\text{cos}(x) + i \text{sin} (x)$$

Inline formulae get correctly aligned to match the baseline of the surrounding text.

$\text{tan}(\phi) = \frac{\text{sin}(\phi)}{\text{cos}(\phi)}$

The objects of $\ca{Set}$ are sets and its arrows are functions.
For any set $A$ we identify $\idarr{A}$ with the identity function on $A$, $\id : A \to A$.
$\circ$ is indeed associative.

Each [poset](https://en.wikipedia.org/wiki/Partially_ordered_set) is a category.

The objects of each poset are its elements and we construct an arrow $\arr{a}{\leq}{b}$ for every pair of objects $(a, b)$ iff $a \leq b$.
Reflexivity ($a \leq a$) and transitivity ($a \leq b \land b \leq c \implies a \leq c$) provide a construction for $\idarr{a}$ and $\circ$, respectively.

Each [monoid](https://en.wikipedia.org/wiki/Monoid) is a category.

]]>
The objects of each monoid are its elements and we construct for every pair of elements $(a, b)$ an arrow $\arr{a}{\cdot b}{a \cdot b}$.
The existence of an identity element and associativity, as required by the monoid structure, immediately provide us with a construction for $\id$ and associativity of $\circ$.

$\id$ on $A$ is indeed a function which preserves the structure ($\id \circ \alpha = \alpha = \alpha \circ \id$, $\id(a) = a$) and thus a morphism

2. There exists an associative partial binary operation $\circ$ on the arrows of $\ca{Pno}$
Given three objects $(A, \alpha, a), (B, \beta, b), (C, \gamma, c)$ and two functions $g: A \to B$ and $f: B \to C$ the function $f \circ g: A \to C$ is an arrow in $\ca{Pno}$, that is to say, it preserves structure:
$$(f \circ g) \circ \alpha = f \circ \beta \circ g = \gamma \circ (f \circ g)$$
and
$$(f \circ g)(a) = f(b) = c$$

b) Show that $(\N, \textrm{succ}, 0)$ is a $\ca{Pno}$-object
$\N$ is indeed a Set, $\textrm{succ}$ is indeed an unary function and $0$ is indeed an element of $\N$.

c) Show that for each $\ca{Pno}$-object $(A, \alpha, a)$ there is an unique arrow
$$\arr{(\N, \textrm{succ}, 0)}{}{(A, \alpha, a)}$$
and describe the behaviour of the carrying function.
We construct a carrying function recursively:
$$\begin{aligned}
f : \N & \to A \\
0 & \mapsto a \\
\textrm{succ}(x) & \mapsto \alpha(f(x))
\end{aligned}$$
$f : \N \to A$ is indeed a morphism and thus an arrow.
Given two morphisms $f : \N \to A$ and $g : \N \to A$ we show that they are pointwise identical by induction over $\N$:
* $f(0) = a = g(0)$
* Given $n \in \N$:
$$(f \circ \mathrm{succ})(n) = (\alpha \circ f)(n) \overset{\text{ind.}}{=} (\alpha \circ g)(n) = (g \circ \mathrm{succ})(n)$$
The morphism maps $\N$ to the transitive closure of $a$ under $\alpha$.

Consider objects of form $(A, a)$ where $A$ is a set and $a \subseteq A$.
For two such objects a morphism $\arr{(A, a)}{f}{(B, b)}$ is a function $f : A \to B$ that respects the selected subsets:
$$\forall \alpha \in a \ldotp f(\alpha) \in b$$
Show that such objects and morphisms form a category $\ca{SetD}$
1. For every $(A, a) \in \ca{SetD}$ there exists $\idarr{(A, a)}$

$\id$ on $A$ is indeed a function which respects the distinguished subset ($\forall \alpha \in a \ldotp \id(\alpha) \in a$) and thus a morphism

2. There exists an associative partial binary operation $\circ$ on the arrows of $\ca{SetD}$
Given three objects $(A, a), (B, b), (C, c)$ and two functions $g: A \to B$ and $f: B \to C$ the function $f \circ g: A \to C$ is an arrow in $\ca{SetD}$, that is to say, $\forall \alpha \in a$:
$$(f \circ g)(\alpha) = f(b) = c$$

Consider pairs $(A, \odot)$ where $A$ is a set and $\odot \subseteq A \times A$ is a binary relation on $A$.
Show that these pairs are objects of a category finding a sensible notion of morphism.

For two such objects $(A, \odot), (B, \oplus)$ a morphism shall be a function $f : A \to B$ that respects the binary relation:
$$\forall a \odot a^\prime \ldotp f(a) \oplus f(a^\prime)$$
We call the category comprised of such objects and arrows $\ca{RelH}$.
1. For every $(A, \odot) \in \ca{RelH}$ there exists $\idarr{(A, \odot)}$
$\id$ on $A$ is indeed a function which respects the binary relation ($\forall a \odot a^\prime \ldotp \id(a) \odot \id(a^\prime)$) and thus a morphism
2. There exists an associative partial binary operation $\circ$ on the arrows of $\ca{RelH}$
Given three objects $(A, \odot), (B, \oplus), (C, \otimes)$ and two functions $g: A \to B$ and $f: B \to C$ the function $f \circ g: A \to C$ is an arrow in $\ca{RelH}$, that is to say, $\forall a \odot a^\prime$:
$$a \odot a^\prime \implies g(a) \oplus g(a^\prime) \implies (g \circ f)(a) \otimes (g \circ f)(a^\prime)$$

Topological spaces $(S, \mathcal{O}_S)$, where $S$ is a Set and $\mathcal{O}_S \subseteq \powerset{S}$, and continuous maps $f : S \to P$, that is $\forall V \in \mathcal{O}_T \ldotp f^\leftarrow(V) \in \mathcal{O}_S$, form a Category $\ca{Top}$.
1. For every $(S, \mathcal{O}_S) \in \ca{Top}$ there exists $\idarr{(S, \mathcal{O}_S)}$

$\id$ on $S$ is indeed a continuous map and thus a morphism

2. There exists an associative partial binary operation $\circ$ on the arrows of $\ca{Top}$
Given three spaces $(S, \mathcal{O}_S), (T, \mathcal{O}_T), (U, \mathcal{O}_U)$ and two continuous maps $g : S \to T$ and $f : T \to U$ the map $f \circ g : S \to U$ is an arrow in $\ca{Top}$, that is to say, it is contiuous:
$$V \in \mathcal{O}_U \implies g^\leftarrow(V) \in \mathcal{O}_T \implies (f \circ g)^\leftarrow(V) \in \mathcal{O}_S$$

Show that $\End{\ca{C}}{A}$ is a monoid under composition, where $A$ is an object of a category $\ca{C}$.

$\circ$ is associative and total on $\End{\ca{C}}{A}$ by the definition of category and $\End{\ca{C}}{A}$ is obviously closed under $\circ$.
$\idarr{A}$ is required to exist by the definition of category and indeed an identity of $\circ$ on $\End{\ca{C}}{A}$.

Each monoid $(M, \cdot)$ is a category ([again](./1.1.md)).

We construct a category with exactly one object $\ast$ and associate to every element $m \in M$ an arrow $\arr{\ast}{m}{\ast}$.
We further define $m \circ n = m \cdot n$.

Show that $\circ$ in $\ca{Pfn}$ is associative.

Consider the composition $g \circ f = \rest{g}{\bar{B}} \circ \rest{f}{\bar{\bar{A}}}$ of two partial functions $f : A \to B$ and $g : B \to C$:
$$
\begin{tikzcd}
A \arrow[r, "f"] & B \arrow[r, "g"] & C \\
\bar{A} \arrow[u, hook] \arrow[ru, "\rest{f}{\bar{A}}" description] & \bar{B} \arrow[u, hook] \arrow[ru, "\rest{g}{\bar{B}}" description] & \\
\bar{\bar{A}} \arrow[u, hook] \arrow[ru, "\rest{f}{\bar{\bar{A}}}" description] & & \\
\end{tikzcd}
$$
where all restricted versions of $f$, $g$, and $h$ are total.
Extending the above to three partial functions $f : A \to B$, $g : B \to C$, and $h : C \to D$:
$$
\begin{aligned}
(h \circ g) \circ f &= \rest{\left (\rest{h}{\bar{C}} \circ \rest{g}{\bar{\bar{B}}} \right )}{\bar{B}} \circ \rest{f}{\bar{\bar{A}}} \\
&= \rest{h}{\bar{C}} \circ \rest{g}{\bar{\bar{B}}} \circ \rest{f}{\bar{\bar{A}}} \\
&= \rest{h}{\bar{C}} \circ \rest{\left (\rest{g}{\bar{\bar{B}}} \circ \rest{f}{\bar{\bar{A}}} \right)}{\bar{\bar{A}}} \\
&= h \circ (g \circ f)
\end{aligned}
$$

Consider the category $\ca{Set_\bot}$ of pointed sets.
Show that $\ca{Set_\bot}$ and $\ca{Pfn}$ are "essentially the same" category.

The idea is to identify the undefined parts of a partial functions image with $\bot$:
$$
\begin{aligned}
\Phi : \ca{Pfn} & \to \ca{Set_\bot} \\
A & \mapsto A \cup \{ \bot_A \} \\
f\ \text{s.t.} \begin{tikzcd}
A \arrow[r, "f"] & B \\
\bar{A} \arrow[u, hook] \arrow[ru, "\rest{f}{\bar{A}}" description] &
\end{tikzcd} & \mapsto \begin{aligned}
\Phi(f) : A \cup \{ \bot_A \} & \to B \cup \{ \bot_B \} \\
\bot_A & \mapsto \bot_B \\
a & \mapsto \begin{cases}
f(a) & \quad x \in \bar{A} \\
\bot & \quad \text{else}
\end{cases}
\end{aligned} \\
\Phi^\leftarrow : \ca{Set_\bot} & \to \ca{Pfn} \\
A & \mapsto A - \{ \bot \} \\
\arr{A}{f}{B} & \mapsto \rest{f}{\left ( A - \{ \bot \} \right )}
\end{aligned}
$$
where $\rest{f}{\bar{A}}$ is total.

Verify that for every monoid $R$ both $R\ca{Set}$ and $\ca{Set}R$ are categories of structured sets.

]]>
Since the two proofs are perfectly analogous we cover only the case $R\ca{Set}$.
1. For every $R$-Set $A \in R\ca{Set}$ there exists $\idarr{A}$
$\id$ on $A$ is indeed a structure preserving function ($\forall a \in A, r \in R \ldotp \id(ra) = ra = r \id(a)$).
2. There exists an associative partial binary operation $\circ$ on the arrows of $R\ca{Set}$
Given three R-Sets $A$, $B$, and $C$ and two continuous maps $g : A \to B$ and $f : B \to C$ the map $f \circ g : A \to C$ is an arrow in $R\ca{Set}$, that is to say $\forall a \in A, r \in R$:
$$(f \circ g)(ra) = f(r g(a)) = r (f \circ g)(a)$$
The format of the proof was chosen to demonstrate that $R\ca{Set}$ is indeed a structured set.