<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>groupoid.moe</title>
  <id>https://groupoid.moe/feed.xml</id>
  <subtitle>Recent posts</subtitle>
  <updated>2022-03-11T00:00:00+00:00</updated>
  <link href="https://groupoid.moe/feed.xml" rel="self"/>
  <link href="https://groupoid.moe"/>
<entry>
  <title>Useful Mac OS programs</title>
  <id>https://groupoid.moe/posts//mac-apps.html</id>
  <author>
   <name>Daniel</name>
  </author>
  <updated>2022-03-11T00:00:00+00:00</updated>
  <link href="https://groupoid.moe/posts//mac-apps.html" rel="alternate" />
  <content type="xhtml">  <div xmlns="http://www.w3.org/1999/xhtml"><p>Somewhat recently I got a MacBook Pro for work[^1]. I already use other
Apple products and I figured that being a UNIX based system it is
going to be very much useable for work related things. And, of course,
I was curious about their new M1 soc. Initially I was a bit dissapointed
coming from Linux/X11, and I was missing a few things.</p>
<p>After some rudimentary research, I found the following programs to be
very useful, and I highly recommend them for improving your
interactions with the Mac OS. All of the programs below are free
software and can be installed using Homebrew.</p>
<p>For GUI/DE:</p>
<ul>
<li><a href="http://www.hammerspoon.org/">Hammerspoon</a> for configuring keyboard
shortcuts for maximazing windows, snapping them around, etc. It is a
general-purpose &quot;automation&quot; tool, and it is scripted in Lua. You
can really do a lot of things with it, and I barely scratch the
surface with my <a href="https://git.groupoid.moe/dan/dotfiles/src/branch/master/hammerspoon/.hammerspoon/init.lua">very modest configuration file</a>.
</li>
<li><a href="https://github.com/dmarcotte/easy-move-resize">Easy Move+Resize</a>
for moving and resizing windows like in Linux/X11 by using
Ctrl-Shift-right mouse and Ctrl-Shift-left mouse and dragging the
window. Super useful. A lot of this is standard in other UNIX systems but why not in MacOS?
</li>
<li>BackgroundMusic for per-app sound
control. I was really surprised this is not implemented by default
in Mac OS.
</li>
<li><a href="https://mos.caldis.me/">Mos</a>. A tool to fix the broken mouse
behavior on Mac OS. In Mac OS you can use two scrolling directions:
&quot;natural scrolling&quot; (which is great for touch pads) and the standard
scrolling (which is great for standard mices). Unfortunately, you
can only select one direction which applies to <em>all</em> of your
devices! So, you need to install Mos to implement the scrolling
properly.
</li>
<li><a href="https://github.com/MonitorControl/MonitorControl">MonitorControl</a>.
Another important feature: being able to control volume and
brightness on external monitors.
</li>
</ul>
<p>For writing anything in LaTeX I use this combo:</p>
<ul>
<li>Mitsuharu Yamamoto's <a href="https://bitbucket.org/mituharu/emacs-mac/src/master/">emacs-mac port</a>,
also available <a href="https://github.com/railwaycat/homebrew-emacsmacport">via homebrew</a>.
It beats the other Emacs ports for MacOS by integrating some
Mac-specific niceties like smooth scrolling, correctly registering
fullscreen, etc. You you install it from source, and you gcc and
libgccjit, you can enable native compilation for elsip.
</li>
<li><a href="http://skim-app.sourceforge.net/">Skim</a> for PDF viewing. Works
flawlessly with Emacs/SyncTeX. Backwards search with
Shift-Command-click.
</li>
</ul>
<p>Other useful programs:</p>
<ul>
<li><a href="https://github.com/exelban/stats">Stats.app</a> for monitoring
resource usage, fans, temperature, etc.
</li>
<li><a href="https://iina.io/">IINA</a>. Basically a frontend to <code>mpv</code>. Great media
player.
</li>
<li><a href="https://iterm2.com/">iTerm2</a>. Easy to use terminal emulator.
</li>
<li>For unknown reason, stock MacOS does not support per-app volume
settings. Even as a frequent hater of the audio on Linux, I have to
admit that this just puzzled me. You need to donwload a separate
app, BackgroundMusic, and route all of your audio throught it.
</li>
</ul>
<p>[^1]: I wrote this post a few years ago, and I updated it a bit more recently.</p>
  </div></content>
</entry>

<entry>
  <title>Leibniz equality for truncated types in HoTT</title>
  <id>https://groupoid.moe/posts//leibniz-equality.html</id>
  <author>
   <name>Daniel</name>
  </author>
  <updated>2021-01-19T00:00:00+00:00</updated>
  <link href="https://groupoid.moe/posts//leibniz-equality.html" rel="alternate" />
  <content type="xhtml">  <div xmlns="http://www.w3.org/1999/xhtml"><p>Leibniz equality states that two things are equal if they are
industinguishable by any predicates. For a type <code>A</code> and <code>a, b : A</code>:</p>
<pre><code>Leq(A, a, b) ≡ ∏ (P : A → Prop), P a ⇔ P b
</code></pre>
<p>In the language of HoTT we can restate the definition slightly:</p>
<pre><code>Leq(A, a, b) ≡ ∏ (P : A → hProp), P a = P b
</code></pre>
<p>where the last equality is equality of hProps: <code>P a =_hProp P b</code>.
Since <code>hProp : hSet</code>, we have that <code>P a =_hProp P b : hProp</code> and,
hence <code>Leq(A, a, b) : hProp</code>.</p>
<p>Because <code>Leq</code> is a proposition it cannot describe fully the actual
identity type <code>Id(A, a, b)</code>. But it does accurately desctibe the
equality in hSets.</p>
<p>Let <code>A : hSet</code>. Then we can define <code>Leq(A, a, b) &lt;-&gt; Id(A, a, b)</code>.
First, we define <code>f : Id(A, a, b) → Leq(A, a, b)</code> by</p>
<pre><code>f(p : a = b) ≡ λ (P : A → hProp). ap P p
</code></pre>
<p>In the other direction we define <code>g : Leq(A, a, b) → Id(A, a, b)</code>.
Suppose we have <code>H : Leq(A, a, b)</code>. Then we just pick <code>h(x) ≡ (a = x)</code>,
and <code>H(h) : (a = a) = (a = b)</code>, which we apply to <code>1_a</code>.</p>
<pre><code>g(H : ∏ P, P a = P b) ≡
    let h = (λx. a = x) : A → hProp in
    transport (λ X. X) (H(h)) (idpath a)
</code></pre>
<p>So, for the equality on <code>hSet</code>s, the Leibniz equality coincides with
the ML indentity type.</p>
<p>The question that I have is whether we can generalize it and define a
complete tower of Leibniz equalities?
This is what I mean, specifically.</p>
<p>For an (n+1)-Type <code>A</code> and <code>a, b : A</code>, we can define <code>Leq_n(A, a, b) : n-Type</code> as:</p>
<pre><code>Leq_n(A, a, b) ≡ ∏ (P : A → n-Type), P a =_{n-Type} P b
</code></pre>
<p>We can still reuse the same functions <code>f</code> and <code>g</code>, which type check
correctly. We can also show:</p>
<pre><code>g(f(p : a = b)) = p
</code></pre>
<p>By induction</p>
<pre><code>g(f(1_a)) = g(λP. ap P 1_a) = g (λP. 1_{P_a}) =
(idpath (h(a) = h(a)))*(1_a) = 1_a
</code></pre>
<p>So we have a section <code>a = b → Leq_n(A, a, b)</code>. But showing that <code>f(g(H)) = H</code> is complicated. It would be nice to see if it can be derived
somehow.</p>
<p>In order to show that <code>f(g(H)) = H</code>, you need to show that for any <code>P</code>,</p>
<pre><code>ap P (transport (H (λx. a = x)) 1a) = H P
</code></pre>
<p>Note that all the elements in the image of <code>f</code> satisfy this condition.
So perhaps it will make sense to restrict the type <code>Leq(A, a, b)</code> to
contain only such <code>H</code>s that satisfy the condition above?
I am not sure, but it is something that might be worth looking into.</p>
<p>Note that the definition of Leibniz equality that we consider here is different from the &quot;unrestricted&quot; Leibniz equality:</p>
<pre><code>Leq_Type(A, a, b) ≡ ∏ (P : A → Type), P a ↔ P b
</code></pre>
<p>This Leibniz equality type has been studied in the context of intensional type theory in <a href="https://www.cambridge.org/core/journals/journal-of-functional-programming/article/abs/leibniz-equality-is-isomorphic-to-martinlof-identity-parametrically/50D76A9C314AB24E7CD46DA4A0A766EB">&quot;Leibniz equality is isomorphic to Martin-Löf identity, parametrically&quot;</a> by Abel, Cockx, Devriese, Timany, and Wadler.
They show that, under the assumptions of parametricity/under the parametricity translation, the above <code>Leq_Type</code> is isomorphic to the standard intensional equality type.</p>
<p>It might be interesting to compare the &quot;truncated&quot; and &quot;unrestricted&quot; Leibniz equality types.
For example, we can represent a type as a <a href="https://homotopytypetheory.org/2014/06/30/fibrations-with-em-fiber/">colimit of a sequence of n-truncations</a>.
Does this connection somehow lift to representation of <code>Leq_Type</code> in terms of <code>Leq_n</code>'s?</p>
<p>Let me know if you have any ideas on this topic.</p>
  </div></content>
</entry>

<entry>
  <title>Counterexamples of algebraic theories</title>
  <id>https://groupoid.moe/posts//alg-theories-examples.html</id>
  <author>
   <name>Daniel</name>
  </author>
  <updated>2020-01-21T00:00:00+00:00</updated>
  <link href="https://groupoid.moe/posts//alg-theories-examples.html" rel="alternate" />
  <content type="xhtml">  <div xmlns="http://www.w3.org/1999/xhtml"><p>An <em>algebraic theory</em> $T$ is given by a collection of operations with
given arities, and a number of equations of the form $\Gamma \mid t =
s$ between terms of $T$. Here $t$ and $s$ can contain free variables
from $\Gamma$. A model $M$ for an algebraic theory $T$ is an
underlying set (call it $M$ as well) which interprets all the
operations, and for which all the equations of $T$ hold. A morphism of
$T$-models is a function of the underlying sets that presevres the
interpretation of all the operations.</p>
<p>The category $Mod_T$ of $T$-models comes with a forgetful functor $U :
Mod_T \to Set$. It has a left adjoint $F : Set \to Mod_T$ which
constructs a free $T$-model on the underlying set.</p>
<p>The category $Mod_T$ and the functor $U$ always satisfies a number of
properties that can be used for showing that certain theories are not
algebraic, i.e. that certain categories do not arise as models of
algebraic theories.</p>
<h2 id="conservativity-of-the-forgetful-functor">Conservativity of the forgetful functor</h2>
<p>One of the properties of $U$ is that it reflects isomorphisms: if $f :
M \to M'$ is a morphism of $T$-models, and $f$ has a set-theoretic
inverse $g$ (i.e. $g : M' \to M$ such that $U(f) \circ g = 1$ and $g
\circ U(f) = 1$), then $f$ is an isomorphism of models.</p>
<p>This can be easily observed for monoids: let $f$ be a group
homomorphism and let $g$ be it's set theoretic inverse. Then $g(ab) =
g(f(g(a)) f(g(b))) = g (f (g(a)g(b))) = g(a)g(b)$.</p>
<p><strong>Posets</strong>. A discrete two-element poset $X = \{0,1\}$ can be embedded
into the poset $Y = \{0, 1\}$ with $0 \leq_Y 1$. Moreover, on a
set-theoretic level, this injection is just an identity function and
hence is an isomorphism. If the theory of posets were algebraic, then
$X$ and $Y$ were isomorphic as posets, which is not the case.</p>
<h2 id="lattice-of-submodels">Lattice of submodels</h2>
<p>Up to isomorphism, a subobject of a $T$-model $M$ is a $T$-model $M'$
such that $M' \subseteq M$ and the interpretation of all the
operations on $M'$ coincides with the interpretations in $M$.</p>
<p>Like in many categories, subobjects for a given model form a lattice.
The meet of submodels is just a set-theoretic intersection (can be
computed from the pullback of one submodel along the other). However,
the join of two submodels may not coincide with the set-theoretic
union: if we have two submodels $M_1, M_2$, and a binary operation $f$
in the theory, then the set-theoretic union $M_1 \cup M_2$ will not
contain $\bar{f}(x, y)$ for $x \in M_1, y \in M_2$ and $\bar{f}$ the
interpretation of $f$ in $M$.</p>
<p>Given a set $X \subseteq M$ we define the <em>closure of $X$</em> to be the
smallest submodel $\bar{X} \subseteq M$ that contains $X$. Explicitly,
$$
\bar{X} = \{ \bar{f}(x_1, \dots, x_n) \in M \mid x_1, \dots, x_n \in X, f \in T \}
$$
where $\bar{f}$ is a $M$-interpretation of an $n$-ary operation $f$ from $T$.
$\bar{X}$ behaves like the closure operation and satisfies all the expected properties.</p>
<p>Using the closure operation we can define the join of two submodels $M_1, M_2 \subseteq M$ as
$$M_1 \vee M_2 = \overline{M_1 \cup M_2}$$.
This can be generalized to unions over arbitrary families $\bigvee_{i \in \mathcal{I}} M_i$.</p>
<p>Finally, note the following: if $M_i, i \in \mathcal{I}$ is a directed family, then $\bigvee_{i \in \mathcal{I}} M_i = \bigcup_{i \in \mathcal{I}} M_i$.
If at some point we add $\bar{f}(a, b)$ to the join, with $a \in M_a, b \in M_b$, then there is some $M_c$ that includes both $M_a$ and $M_b$; this submodel $M_c$ already contains $\bar{f}(a, b)$.</p>
<p>Now we are ready to give another counterexample.</p>
<p><strong>Complete lattices</strong>. The theory of complete lattices in not algebraic.
Consider the completion $\omega+1$ of $\omega$ with the top element $\infty$.
Consider a directed family $D = \{ \{ 0, \dots, n \} \mid n \in \mathbb{N} \}$.
The set-theoretic union $\bigcup D$ is just the natural numbers (not a complete lattice), but the join $\bigvee D$ is $\omega+1$.</p>
  </div></content>
</entry>

<entry>
  <title>HD44780 LCD with OCaml</title>
  <id>https://groupoid.moe/posts//adafruit-lcd.html</id>
  <author>
   <name>Daniel</name>
  </author>
  <updated>2019-08-28T00:00:00+00:00</updated>
  <link href="https://groupoid.moe/posts//adafruit-lcd.html" rel="alternate" />
  <content type="xhtml">  <div xmlns="http://www.w3.org/1999/xhtml"><p>Some time ago I've purchased an <a href="https://www.adafruit.com/product/181">Adafruit HD44780
LCD</a> as a fancy accessory for
playing around with Raspberry Pi. It was lying around in my office for
some time until recently. I finally got around to putting it together
(many thanks to my office mate Carlo for helping me solder and wire the
thing).</p>
<p>It came with a <a href="https://github.com/adafruit/Adafruit_CircuitPython_CharLCD">Python
library</a>
for controlling it via a high-level API. However, I don't really like
Python, and I really don't like the design of CircuitPython. So I
decided to write an interface to the LCD in OCaml, that I originally
wanted to use on a Raspberry Pi (using the bindings to the WiringPi
library).</p>
<p>The code can be found in <a href="https://github.com/co-dan/ocaml-wiringpi/tree/lcd_lwt/examples">my fork of the ocaml-wiringpi repository</a> under the <code>lcd_lwt</code> branch.
It mainly consists of two parts:
the low-level interface for writing data to the display and invoking
some operations, and a high-level interface powered by a &quot;cursor&quot;
module.</p>
<h2 id="the-basics">The basics</h2>
<p>The first is a low-level API that controls the display using 4 data
pins (D4-D7) and two special &quot;control&quot; pins. The first control pin is EN
(&quot;enable pin&quot;) which is used to signal the start of data read/write
operations. The RS (&quot;register select pin&quot;) is used as a flag for
selecting which registers to address. The low value denotes the
instruction register, and the high value denotes the data register.</p>
<p>For example, to clear the display (instruction 0x01 = 0b00000001) one would send the following signals
to the LCD:</p>
<ol>
<li>send 0 to RS
</li>
<li>send 0, 0, 0, 0 to D4, D5, D6, D7, resp   --  the four upper bits in reverse order
</li>
<li>send 0, 1, 0 to EN -- signal that the first four bits have been sent
</li>
<li>send 1, 0, 0, 0 to D4, D5, D6, D7, resp   --  the four lower bits in reverse order
</li>
<li>send 0, 1, 0 to EN -- signal that the last four bits have been sent
</li>
</ol>
<p>Internally, this sequence of signals stores 0b00000001 in the instruction register IR.</p>
<p>Instead of sending the instructions to the LCD, we can instead send
data, which ends up in the display data RAM (DDRAM). Suppose we want
to display a character 'a' (ascii 97 = 0b1100001). We then do the
following sequence of operations:</p>
<ol>
<li>send 1 to RS -- address the data register
</li>
<li>send 0, 0, 1, 1 to D4, D5, D6, D7, resp   --  the four upper bits in reverse order
</li>
<li>send 0, 1, 0 to EN -- signal that the first four bits have been sent
</li>
<li>send 0, 0, 0, 1 to D4, D5, D6, D7, resp   --  the four lower bits in reverse order
</li>
<li>send 0, 1, 0 to EN -- signal that the last four bits have been sent
</li>
</ol>
<p>We implement this operation of writing 8 bits to either the
instruction register or the data register as the following function:</p>
<pre><code class="language-ocaml">write8 : Lcd.t -&gt; ?char_mode:bool -&gt; char -&gt; unit
</code></pre>
<p>where <code>char_mode</code> determines whether we write the data to the data
register (<code>true</code>) or to the instruction register (<code>false</code>).</p>
<p>To write out a string to be displayed we can use <code>Bytes.iter</code>:</p>
<pre><code class="language-ocaml">let write_bytes lcd bts =
  Bytes.iter (fun c -&gt; write8 lcd c ~char_mode:true) bts
</code></pre>
<p>The location in which we store the data is determined by the address
counter, which is automatically incremented after each write. This
means that we can just send a sequence of characters sequentially,
without touching the address counter ourselves.</p>
<h2 id="operations-with-arguments">Operations with arguments</h2>
<p>The way that operations with arguments are typically represented is by
using e.g. 4 bits to denote the operation and 4 bits to denote the
arguments. For instance, to activate the 2 line mode, we invoke the
&quot;function set&quot; operation which requires the upper 4 bits to be <code>0010</code>,
with the argument &quot;2 line mode&quot; which requires the lower 4 bits to be
<code>1000</code>. To obtain the code for the whole operation we just take the
bitwise OR:</p>
<pre><code>0b0000 1000 -- 2 line mode
0b0010 0000 -- function set
___________
0b0010 1000
</code></pre>
<p>This translates to the following mini program in OCaml:</p>
<pre><code>let _lcd_2line               = (0x08) in
let _lcd_functionset         = (0x20) in
write8_unsafe lcd (_lcd_2line lor _lcd_functionset);
</code></pre>
<p>Let us a consider a simple example: shifting the characters.
By default, the data that is actually displayed on the LCD is taken
from the addresses 0x0..0x7 and 0x40..0x47 for the first and the
second rows, resp. If we want to display further characters we can use
this shift operation. (See FIGURE 5 in the docs).</p>
<p>To do this we invoke the &quot;cursor/display shift&quot; operation settin the
appropriate bits for moving the display and the move direction:</p>
<pre><code>let _lcd_cursorshift         = (0x10)
(* 00010000 *)
let _lcd_displaymove         = (0x08)
(* 00001000 *)
let _lcd_moveright           = (0x04)
(* 00000100 *)
(* -------- *)
(* 00011100 *)

let shift_right lcd =
  write8_unsafe lcd (_lcd_cursorshift lor _lcd_displaymove lor _lcd_moveright)
</code></pre>
<h2 id="higher-level-interface">Higher-level interface</h2>
<p>We can provide a slightly higher-level interface by keeping track of the cursor (and some other settings) in the program.</p>
<pre><code class="language-ocaml">  type Cursor.t = { x: int; y: int; visible: bool; blink: bool; _lcd: mono_lcd }
</code></pre>
<p>A /cursor/ is a record that combines the underlying <code>mono_lcd</code> type (which stores the pin layout), the current position of the cursor <code>x, y</code> and some settings (whether the cursor should be visible and blinking).
Then all the operation on the cursor are just functions <code>Cursor.t -&gt; Cursor.t</code>.
For example, a function that write out a string takes in a cursor, writes the underlying bytes using <code>write_bytes</code> and updates the cursor position.
A function that sets the blinking flag writes out the desired bytes (as descirbed in the &quot;operations with arguments&quot;) and updates the boolean flag.
Combination of those operations are just function composition:</p>
<pre><code class="language-ocaml">let (|&gt;) (m : Cursor.t) (f : Cursor.t -&gt; 'b) = f m
let display_lines lcd l1 l2 =
  let col_shift = 3 in
  clear lcd;
  let cur = Cursor.of_lcd lcd in
  let open Cursor in
  cur
  |&gt; set_visible false
  |&gt; set_blink false
  |&gt; set_position col_shift 0 
  |&gt; write_string l1 ~wrap:false
  |&gt; set_position col_shift 1
  |&gt; write_string l2 ~wrap:false
</code></pre>
<h2 id="concluding">Concluding</h2>
<p>You can find more usage examples in the <a href="https://github.com/co-dan/ocaml-wiringpi/blob/lcd_lwt/examples/lcd_lwt.ml">lcd_lwt.ml file</a>.
Overall, I thought that OCaml was a good fit for this kind of programming, and the type system helps out a bit!</p>
  </div></content>
</entry>

<entry>
  <title>Delimited continuations</title>
  <id>https://groupoid.moe/posts//delim.html</id>
  <author>
   <name>Daniel</name>
  </author>
  <updated>2018-12-01T00:00:00+00:00</updated>
  <link href="https://groupoid.moe/posts//delim.html" rel="alternate" />
  <content type="xhtml">  <div xmlns="http://www.w3.org/1999/xhtml"><p>A continuation can be understood as a context that represents the
“rest of the program”. Notice that formulated in this way,
continuation is a meta-level abstraction. Ability to manipulate such
continuations as functions is obtained using <em>control operators</em>. The
Scheme programming language has traditionally been a ripe field for
research on control operators such as <code>(call/cc)</code>.</p>
<p>Call-with-current-continuation is an example of an unbounded control
operator. A different and a more general class of control operators
are <em>delimited control operators</em>. The basic idea is that rather to
capture the whole rest of the program as a continuation, delimited
control operators capture delimited continuations, i.e. some part of
the program with a hole.</p>
<p>In order to run the examples from this document in <a href="http://racket-lang.org">DrRacket</a> make sure to put
<code>(require racket/control)</code> in your file.</p>
<h2 id="promptcontrol">Prompt/control</h2>
<p>One of the first (and simplest) delimited control operations is
prompt/control. <code>prompt</code> delimits the continuation, and <code>control</code>
captures the current continuation (up to the innermost <code>prompt</code>).</p>
<pre><code>(prompt (+ 1 (control k (k 3))))
</code></pre>
<p>The code is evaluated as follows:</p>
<pre><code>(prompt (+ 1 (control k (k 3))))
=&gt; (prompt ((λ (k) (k 3)) (λ (x) (+ 1 x))))
=&gt; (prompt ((λ (x) (+ 1 x)) 3)) 
=&gt; (prompt (+ 1 3)) =&gt; (prompt 4) =&gt; 4
</code></pre>
<p>Here <code>(λ (x) (+ 1 x))</code> represents the delimited continuation (the
program inside <code>prompt</code> without the <code>control</code> part) on an object
level. When <code>(control k body)</code> is evaluated inside a <code>prompt</code>, it gets
replaced with <code>(λ (k) body)</code> (capturing <code>k</code> inside <code>body</code>) and applied
to the continuation. In terms of reduction semantics one would have
the <a href="https://docs.racket-lang.org/reference/cont.html#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt%29%29">following reduction rules</a>:</p>
<pre><code>(prompt v) -&gt; v
(prompt E[(control k body)]) -&gt; (prompt ((λ (k) body) (λ (x) E[x])))
</code></pre>
<p>where the evaluation context E does not contain <code>prompt</code> and <code>x</code> is a
free variable in E.</p>
<p>In particular, if continuation is not invoked in <code>body</code>, it is just
discarded, as in the following example:</p>
<pre><code>(prompt (+ 1 (control k 3)))
</code></pre>
<p>A captured delimited continuation can be invoked multiple times:</p>
<pre><code>(prompt
  (+ 1 (control k (let ([x (k 1)] [y (k 2)])
                     (k (* x y))))))
</code></pre>
<p>In this case the continuation <code>k = (λ (x) (+ 1 x))</code>, so when it is
invoked in the body of <code>control</code>, x and y get set to 2 and 3,
respectively. Hence, the final result of that program is 1+2*3=7.</p>
<p>Nested continuations</p>
<pre><code>(prompt
    (+ 2 (control k (+ 1 (control k1 (k1 6))))))
=&gt; (prompt
      ((λ (x) (+ 2 (control k (+ 1 x)))) 6))
=&gt; (prompt
      (+ 2 (control k (+ 1 6))))
=&gt; (prompt
      (+ 2 (control k 7)))
=&gt; (prompt 7) =&gt; 7
</code></pre>
<h2 id="while-loops-with-breaks">While loops with breaks</h2>
<p>We can utilize the prompt/control operators to implement a simple
macro for a while loop with an ability to break out of it, sort of
similar to the while/break statements in C.</p>
<pre><code>(define-syntax-rule (break) (control k '()))
(define-syntax-rule (while cond body ...)  
  (prompt
   (let loop ()
     (when cond
       body ...
       (loop)))))
</code></pre>
<p>We define the <code>(while)</code> construct as a simple recursive loop with just
one caveat – we wrap the whole thing in a <code>prompt</code>. Then <code>(break)</code>,
when evaluated, just discards the whole continuation with is bound to
the <code>(while)</code> loop. We can test this macro by writing a procedure that
multiplies all the elements in the list.</p>
<pre><code>(define (multl lst)
  (define i 0)
  (define fin (length lst))
  (define res 1)
  (while (&lt; i fin)
    (let ([val (list-ref lst i)])
      (printf &quot;The value of lst[~a] is ~a\n&quot; i val)
      (set! res (* res val))
      (when (= val 0)
          (begin (set! res 0) (break))))
    (set! i (+ i 1)))
  res)
</code></pre>
<p>By running this program we can observe that it finishes early whenever
it encounters a zero in the list:</p>
<pre><code>&gt; (multl '(1 2 3))
The value of lst[0] is 1
The value of lst[1] is 2
The value of lst[2] is 3
6
&gt; (multl '(1 2 0 3 4 5))
The value of lst[0] is 1
The value of lst[1] is 2
The value of lst[2] is 0
0
&gt; 
</code></pre>
<p><em>The situation with <code>break</code> in C is slightly different; as it has
been pointed out to me, break is a <em>statement</em>, whereas in our toy
example <code>break</code> is an expression. Due to the dichotomy of statements
and expressions in C this example is not very faithful to C semantics.</em></p>
<h3 id="prompt-tags">Prompt tags</h3>
<p>The <code>(while)</code> macro that we have is actually buggy. The problem arises
when the body of the while loop contains an additional prompt
delimiter:</p>
<pre><code>(while (&lt; i 3) (writeln &quot;Hi&quot;) (prompt (break)) (set! i (+ i 1)))
</code></pre>
<p>When running this example “Hi” is written to the standard output three
time. Oops. To circumvent this problem we can use the <a href="https://docs.racket-lang.org/reference/cont.html#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt-at%29%29">tagged
prompt-at/control-at operators</a> with the following reduction semantics:</p>
<pre><code>(prompt-at tag v) -&gt; v
(prompt-at tag E[(control-at tag' k body)]) -&gt; (prompt-at tag ((λ (k) body) (λ (x) E[x])))
</code></pre>
<p>where <code>tag = tag'</code> and <code>E</code> does not contain <code>prompt-at tag</code>. So the
only difference between prompt-at/control-at and prompt/control is the
presence of <a href="https://docs.racket-lang.org/reference/cont.html#%28def._%28%28quote._~23~25kernel%29._continuation-prompt-tag~3f%29%29">prompt tags</a> which allows for a more fine-grained matching
between delimiters and control operators.</p>
<p>We can sort of fix our while macro by creating a special tag</p>
<pre><code>(define while-tag (make-continuation-prompt-tag 'tagje))
(define-syntax-rule (break) (control-at while-tag k '()))
(define-syntax-rule (while cond body ...)  
  (prompt-at while-tag
   (let loop ()
     (when cond
       body ...
       (loop)))))
</code></pre>
<p>The following program then prints “Hi” only once.</p>
<pre><code>(define i 0)
(while (&lt; i 3) (writeln &quot;Hi&quot;) (prompt (break)) (set! i (+ i 1)))
</code></pre>
<h2 id="resetshift">Reset/shift</h2>
<p>The other pair of delimited control operators are <code>shift</code> and <code>reset</code>.</p>
<p><a href="https://docs.racket-lang.org/reference/cont.html#%28form._%28%28lib._racket%2Fcontrol..rkt%29._reset%29%29">The reductions</a> for <code>reset/shift</code> are as follows.</p>
<pre><code>(reset v) -&gt; v
(reset E[(shift k body)]) -&gt; (reset ((λ (k) body) (λ (x) (reset E[x]))))
</code></pre>
<p>where the evaluation context E does not contain <code>reset</code> and <code>x</code> is a
free variable in E. Contrast this with the reduction rules for
<code>prompt/control</code></p>
<pre><code>(prompt v) -&gt; v
(prompt E[(control k body)]) -&gt; (prompt ((λ (k) body) (λ (x) E[x])))
</code></pre>
<p>As you can notice, the difference between the <code>prompt/control</code>
reductions is that in the case when the continuation is captured, it
is wrapped in an additional <code>reset</code>. Thus, any invocation of a bound
delimited continuation <code>k</code> cannot escape to the outer scope.</p>
<p>To observe the practical difference, consider the following example.</p>
<pre><code>(define (skip) '())
(define (bye) (println &quot;Capturing and discarding the continuation...&quot;) 42)
(prompt
 (let ([act (control k (begin
                         (k skip)
                         (k (λ () (control _ (bye))))
                         (k skip)))])
   (act)
   (println &quot;Doing stuff&quot;)))
</code></pre>
<p>If we were to remove the second line <code>(k (λ () (control _ (bye))))</code> in
the begin block, then this program would print “Doing stuff” twice (as
invoking <code>(k skip)</code> binds the dummy function <code>skip</code> to <code>act</code> and
executes <code>(begin (act) (println &quot;Doing stuff&quot;))</code>). With such a line
present, during the invocation of <code>k</code>, <code>act</code> gets bound to <code>(λ () (control _ (bye)))</code>. Therefore, when <code>act</code> is evaluated the
continuation is of the form <code>(prompt E[(control _ bye)])</code>, which just
reduces to <code>(prompt (bye))</code> and <code>(prompt 42)</code>. So, the output of the
program above is</p>
<pre><code>&quot;Doing stuff&quot;
&quot;Capturing and discarding the continuation...&quot;
42
</code></pre>
<p>If we replace <code>prompt</code> with <code>reset</code> and <code>control</code> with <code>shift</code>, as in
the code snippet below, then every invocation of <code>k</code> wraps the
continuation in another <code>reset</code>.</p>
<pre><code>(reset
 (let ([act (shift k (begin
                       (k skip)
                       (k (λ () (shift _ (bye))))
                       (k skip)))])
   (act)
   (println &quot;Doing stuff&quot;)))
</code></pre>
<p>After some reductions, the terms is</p>
<pre><code>(reset 
  ((λ (k) (begin (k skip) (k (λ () (shift _ (bye)))) (K skip))) 
   (λ (x) (reset (begin (x) (println &quot;Doing stuff&quot;))))))
</code></pre>
<p>As you can see, the second invocation of <code>k</code> results in <code>(reset (begin (shift _ (bye)) (println &quot;Doing stuff&quot;)))</code>, and thus</p>
<ol>
<li>“Doing stuff” does not get printed (as this part of the term gets discarded.
</li>
<li>The shift operator discards the <em>inner</em> continuation, not the outer
continuation. In particular, that means that the call to <code>(k (λ () (shift _ (bye))))</code> returns!
</li>
</ol>
<p>The output of the snippet is thus</p>
<pre><code>&quot;Doing stuff&quot;
&quot;Capturing and discarding the continuation...&quot;
&quot;Doing stuff&quot;
</code></pre>
<h2 id="comments-and-further-reading">Comments and further reading</h2>
<p>See references at <a href="https://docs.racket-lang.org/reference/cont.html">https://docs.racket-lang.org/reference/cont.html</a>.</p>
<p>Some interesting papers:</p>
<ul>
<li><a href="http://homes.soic.indiana.edu/ccshan/recur/recur.pdf">Shift to control</a> by C.C. Shan shows how to express shift/reset and control/prompt in terms of each other.
</li>
<li><a href="http://www.brics.dk/RS/05/2/BRICS-RS-05-2.pdf">On the Dynamic Extent of Delimited Continuations</a> by Dariusz
Biernacki and Olivier Danvy present the difference between shift and
control using breadth-first traversal as an example. It is also
explained in which sense <code>shift</code> is a static delimited control
operator and <code>control</code> is a dynamic delimited control operator.
</li>
<li>A bibliography of <a href="http://library.readscheme.org/page6.html">Continuations and Continuation Passing Style</a> at the readscheme.org
</li>
</ul>
  </div></content>
</entry>

<entry>
  <title>Omitting types</title>
  <id>https://groupoid.moe/posts//omitting-types.html</id>
  <author>
   <name>Daniel</name>
  </author>
  <updated>2016-03-15T00:00:00+00:00</updated>
  <link href="https://groupoid.moe/posts//omitting-types.html" rel="alternate" />
  <content type="xhtml">  <div xmlns="http://www.w3.org/1999/xhtml"><p><strong>Definition.</strong> A <em>type</em> $p(x)$ for the theory $T$ is a collection of
formulas with a free variable $x$ consitent with $T$.</p>
<p>-- see Michael Weiss' <a href="https://diagonalargument.com/2019/05/06/non-standard-models-of-arithmetic-1/">explanation of types</a>.</p>
<p><strong>Definition.</strong> A type $p(x)$ is <em>principal</em> if there is a
formula $\alpha(x)$ such that $p(x)=\{ \psi(x) \mid \alpha \vdash \psi \}$</p>
<p><strong>Definition.</strong> A type $p(x)$ is <em>full</em> if for every
formula $\psi(x)$ either $\psi \in p(x)$ or $\neg \psi \in p(x)$.</p>
<p>A full type can be seen as a way of describing an a generic &quot;element&quot;
of a theory. For any model $M$ and an element $m \in M$ we can
consider the full type $p(m)$ generated by $m$. It contains all the formlas
$\psi(m)$ that are true about $m$.</p>
<p><a href="https://en.wikipedia.org/wiki/Type_(model_theory)#The_omitting_types_theorem">Omitting types theorem</a>
says that given a <em>complete</em> countable theory $T$ in a countable
language, there is a model $M$ of $T$ which omits countably-many
non-principal full types.</p>
<p>Why is the non-principal condition needed?</p>
<p>If a theory $T$ is complete, then any model of $T$ realizes all the
full principal types. For if $p(x)$ is a complete principal isolated
by $\psi(x)$, then $T \not\vdash \not \exists x.\psi(x)$, for otherwise the
type $p(x)$ would be inconsistent with $T$. Because $T$ is complete it
must be the case that $T \vdash \exists x. \psi(x)$. Then such $x$
realizes $p(x)$.</p>
<p>What happens if the theory $T$ is not complete?</p>
<p>Then it is not the case that all
models of $T$ realize all the full principle types. For instance take
Peano arithmetic, and take $T_1 = PA + Con(PA)$ and $T_2 = PA + \neg
Con(PA)$. Both $T_1$ and $T_2$ are consistent, thus they have models
$M_1$ and $M_2$. Then denote by $q(x)$ the type generated by the
element $0$ in $M_1$, and by $p(x)$ the type generated by the element
$0$ in $M_2$. Both of those types are isolated by the formula $\phi(x)
:= \neg \exists y. y &lt; x$, because $\phi$ completely determines $0$.
Albeit those types are types for different theories, they are both
types for a common theory $PA$. Furthemore, those types are complete
and isolated. However, one of the types states the consistency of $PA$
and the other one points out the inconsistency of $PA$. Thus both $q$
and $p$ cannot be realized in the same model.</p>
  </div></content>
</entry>

<entry>
  <title>Uniquness of the absurdity proofs in Cartesian closed categories</title>
  <id>https://groupoid.moe/posts//boolean-cat.html</id>
  <author>
   <name>Daniel</name>
  </author>
  <updated>2015-08-12T00:00:00+00:00</updated>
  <link href="https://groupoid.moe/posts//boolean-cat.html" rel="alternate" />
  <content type="xhtml">  <div xmlns="http://www.w3.org/1999/xhtml"><p>Adding the DNE to CCCs collapses them into Boolean algebras:
Suppose $\mathcal{C}$ is a Cartesian closed category.
We can show that if $\mathcal{C}$ has a family of isomorphisms between $A$ and $(A \to 0) \to 0$, then $\mathcal{C}$ is a poset (and a Boolean algebra).</p>
<p><strong>Proposition</strong>.
For any object $A$ of $\mathcal{C}$, $A \times 0 \simeq 0$.</p>
<p><em>Proof</em>.
${\mathit{\mathop{Hom}}}(A \times 0, B) \simeq {\mathit{\mathop{Hom}}}(0 \times A, B) \simeq {\mathit{\mathop{Hom}}}(0, B^A)
\simeq 1$.
Therefore, $A \times 0$ is an initial object in $\mathcal{C}$.
Clearly $(\pi_2, \bot_{A \times 0})$ establishes the isomorphism.</p>
<p><em>Qed</em></p>
<p><strong>Proposition</strong>.
Given a morphism $f : A \to 0$, we can conclude that $A \simeq 0$.</p>
<p><em>Proof</em>.
The isomorphism is witnessed by $(f, \bot_A) : A \to A \times 0 \simeq 0$ (where
$\bot_A : 0 \to A$ is the unique initial morphism).</p>
<p><em>Qed</em></p>
<p>We have seen that given the morphism $f : A \to 0$ we can construct an
iso $A \simeq 0$. In particular, that means that there can be <em>at
most one arrow</em> between $A$ and $0$; interpreting arrows as
&quot;proofs&quot; or &quot;proof object&quot;, that means that in the intuitionistic
calculus there is at most one proof/realizer of the negation (up to
isomorphism).</p>
<p>Now, returning to the original question, how do CCCs with
double-negation elimination look like? Specifically, we want to show
that if in $\mathcal{C}$ there is an isomorphism between $A$ and
$0^{(0^A)}$ for all objects $A$, then the categorical structure
collapses into a Boolean algebra.</p>
<p>We say that a category has <em>double negation elimination</em> if for every $A$, it is the case that $A \simeq 0^{(0^A)}$.</p>
<p><strong>Proposition</strong>.
Given a category with double negation elimination and two morphisms $f, g : A \to B$, it
is the case that $f = g$.</p>
<p><em>Proof</em>.
Let $i$ be the isomorphism between $B$ and $0^{(0^B)}$. Then,
$i \circ f, i \circ g \in {\mathit{\mathop{Hom}}}(A, 0^{(0^B)}) \simeq {\mathit{\mathop{Hom}}}(A \times
(0^B), 0)$.
But the latter set can contain at most one element; thus,
$i \circ f = i \circ g$. Because $i$ is an isomorphism, $f = g$.</p>
<p><em>Qed</em></p>
<p>It might be worth noting that in &quot;standard&quot; cartesian closed
categories, a morphism $i : B \to 0^{(0^B)}$ serve as a coequalizer of
$f$ and $g$. Perhaps stretching the analogy a bit, we can view $i$ as
&quot;equalizes&quot; two constructive proofs of $B$ into a single classical
proof.</p>
<p><strong>See also</strong></p>
<ul>
<li><a href="http://link.springer.com/article/10.1007%2FBF02485724">A categorical characterization of Boolean algebras</a> by M.E. Szabo
</li>
</ul>
  </div></content>
</entry>

<entry>
  <title>GHC API tutorial</title>
  <id>https://groupoid.moe/posts//ghc-api.html</id>
  <author>
   <name>Daniel</name>
  </author>
  <updated>2014-06-18T00:00:00+00:00</updated>
  <link href="https://groupoid.moe/posts//ghc-api.html" rel="alternate" />
  <content type="xhtml">  <div xmlns="http://www.w3.org/1999/xhtml"><h1 id="intro">Intro</h1>
<p><em>Disclamer: these notes have been written a couple of years ago. While
some of the basic facts are still the case, some details may be
subject to change. Trust, but verify!</em></p>
<p>It’s hard to get into writing code that uses GHC API. The API itself is and the number of various functions and options significantly outnumber the amount of tutorials around.</p>
<p>In this note I will try to elaborate on some of the peculiar, interesting problems I’ve encountered during my experience writing code that uses GHC API and also provide various tips I find useful.</p>
<p>Many of the points I make in this note are actually trivial, but nevertheless I made all of the mistakes mentioned in here myself, perhaps due to my naive approach of quickly diving in and experimenting, instead of reading into the documentation and source code.</p>
<p>This note is an adaptation of a <a href="http://parenz.wordpress.com/tag/ghc/">series of my blog posts</a> on the subject.</p>
<p>In order to run examples presented in this note you'll have to</p>
<ol>
<li>Install the <code>ghc-paths</code> library
</li>
<li>Compile the code with <code>ghc -package ghc file.hs</code> OR
</li>
<li>Expose the <code>ghc-7.8.x</code> library: <code>ghc-pkg expose ghc-7.8.2</code>
</li>
</ol>
<p>The up to date Haddocks for GHC are located <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/ghc/index.html">here</a>.</p>
<h1 id="interpreted-compiled-and-package-modules">Interpreted, compiled, and package modules</h1>
<p>There are different ways of bringing contents of Haskell modules into scope, a process that is necessary for evaluating/interpreting bits of code on-the-fly. We will walk through some of the caveats of this process.</p>
<h2 id="interpreted-modules">Interpreted modules</h2>
<p>Imagine the following situation: we have a Haskell source file with code we want to load dynamically and evaluate. That is a basic task in the GHC API terms, but there are actually different ways of doing that.</p>
<p>Let us have a file 'test.hs' containing the code we want to access:</p>
<pre><code class="language-haskell">module Test (test) where
test :: Int
test = 123
</code></pre>
<p>The basic way to get the 'test' data would be to load <code>Test</code> as an interpreted module:</p>
<pre><code class="language-haskell">import Control.Applicative
import DynFlags
import GHC
import GHC.Paths
import MonadUtils (liftIO)
import Unsafe.Coerce
    
main = defaultErrorHandler defaultFatalMessager defaultFlushOut $
    runGhc (Just libdir) $ do
         -- we have to call 'setSessionDynFlags' before doing
         -- everything else
        dflags &lt;- getSessionDynFlags
        -- If we want to make GHC interpret our code on the fly, we
        -- ought to set those two flags, otherwise we
        -- wouldn't be able to use 'setContext' below
        setSessionDynFlags $ dflags { hscTarget = HscInterpreted
                                    , ghcLink   = LinkInMemory
                                    }
        setTargets =&lt;&lt; sequence [guessTarget &quot;test.hs&quot; Nothing]
        load LoadAllTargets
        -- Bringing the module into the context
        setContext [IIModule $ mkModuleName &quot;Test&quot;]
        -- evaluating and running an action
        act &lt;- unsafeCoerce &lt;$&gt; compileExpr &quot;print test&quot;           
        liftIO act
</code></pre>
<p>The reason that we have to use <code>HscInterpreted</code> and <code>LinkInMemory</code> is that otherwise it would compile test.hs in the current directory and leave test.hi and test.o files, which we would not be able to load in the interpreted mode. However, <code>setContext</code>, will try to bring the code in those files first, when looking for the module <code>Test</code>.</p>
<pre><code>$ ghc -package ghc --make Interp.hs
[1 of 1] Compiling Main             ( Interp.hs, Interp.o )
Linking Interp ...
$ ./Interp
123
</code></pre>
<p>Yay, it works! But let's try something fancier like printing a list of integers, one-by-one. For that, we will use an awesome <code>forM_</code> function.</p>
<pre><code>--- the rest of the file is the same 
--- ...
        -- evaluating and running an action
        act &lt;- unsafeCoerce &lt;$&gt; compileExpr &quot;forM_ [1,2,test] print&quot;           
        liftIO act
</code></pre>
<p>When we try to run it:</p>
<pre><code>$ ./Interp
Interp: panic! (the 'impossible' happened)
  (GHC version 7.8.2 for x86_64-apple-darwin):
    Not in scope: ‘forM_’
</code></pre>
<p>Well, fair enough, where can we expect GHC to get the <code>forM_</code> from? We have to bring <code>Control.Monad</code> into the scope in order to do that.</p>
<p>This brings us to the next section</p>
<h2 id="package-modules">Package modules</h2>
<p>Naively, we might want to load <code>Control.Monad</code> in a similar fashion as we did with loading <code>test.hs</code>.</p>
<pre><code class="language-haskell">main = defaultErrorHandler defaultFatalMessager defaultFlushOut $
    runGhc (Just libdir) $ do
        dflags &lt;- getSessionDynFlags
        setSessionDynFlags $ dflags { hscTarget = HscInterpreted
                                    , ghcLink   = LinkInMemory
                                    }
        setTargets =&lt;&lt; sequence [ guessTarget &quot;test.hs&quot; Nothing
                                , guessTarget &quot;Control.Monad&quot; Nothing]
        load LoadAllTargets
        -- Bringing the module into the context
        setContext [IIModule $ mkModuleName &quot;Test&quot;]
  
        -- evaluating and running an action
        act &lt;- unsafeCoerce &lt;$&gt; compileExpr &quot;forM_ [1,2,test] print&quot;
        liftIO act
</code></pre>
<p>Unfortunately, this attempt fails:</p>
<pre><code>Interp: panic! (the 'impossible' happened)
  (GHC version 7.8.2 for x86_64-apple-darwin):
    module ‘Control.Monad’ is a package module
</code></pre>
<p>Huh, what? I thought <code>guessTarget</code> works on all kinds of modules.</p>
<p>Well, it does. But it doesn't &quot;load the module&quot;, it merely sets it as the <em>target for compilation</em>. Basically, it (together with <code>load LoadAllTargets</code>) is equivalent to calling <code>ghc --make</code>. And surely it doesn't make much sense trying to <code>ghc --make Control.Monad</code> when <code>Control.Monad</code> is a module from the base package. What we need to do instead is to bring the compiled <code>Control.Monad</code> module into scope. Luckily it's not very hard to do with the help of the <code>simpleImportDecl :: ModuleName -&gt; ImportDecl name</code> function:</p>
<pre><code class="language-haskell">main = defaultErrorHandler defaultFatalMessager defaultFlushOut $
      runGhc (Just libdir) $ do
           -- we have to call 'setSessionDynFlags' before doing
           -- everything else
          dflags &lt;- getSessionDynFlags
          -- If we want to make GHC interpret our code on the fly, we
          -- ought to set those two flags, otherwise we
          -- wouldn't be able to use 'setContext' below
          setSessionDynFlags $ dflags { hscTarget = HscInterpreted
                                      , ghcLink   = LinkInMemory
                                      }
          setTargets =&lt;&lt; sequence [ guessTarget &quot;test.hs&quot; Nothing ]
          load LoadAllTargets
          -- Bringing the module into the context
          setContext [ IIModule $ mkModuleName &quot;Test&quot;
                     , IIDecl . simpleImportDecl 
                              . mkModuleName $ &quot;Control.Monad&quot; ]
          -- evaluating and running an action
          act &lt;- unsafeCoerce &lt;$&gt; compileExpr &quot;forM_ [1,2,test] print&quot;           
          liftIO act
</code></pre>
<p>And this works like a charm:</p>
<pre><code>$ ./Interp
1
2
123
</code></pre>
<h2 id="compiled-modules">Compiled modules</h2>
<p>What we have implemented so far corresponds to the <code>:load* test.hs</code>
command in GHCi, which gives us the full access to the source code of
the program. To illustrate this let's modify our test file:</p>
<pre><code class="language-haskell">module Test (test) where

test :: Int
test = 123

test2 :: String
test2 = &quot;Hi&quot;
</code></pre>
<p>Now, if we want to load that file as an interpreted module and evaluate
<code>test2</code> nothing will stop us from doing so.</p>
<pre><code>$ ./Interp2
(123,&quot;Hi&quot;)
</code></pre>
<p>If we want to use the compiled module (like <code>:load test.hs</code> in GHCi),
we have to bring <code>Test</code> into the context the same way we dealt with
<code>Control.Monad</code>:</p>
<pre><code class="language-haskell">main = defaultErrorHandler defaultFatalMessager defaultFlushOut $
  runGhc (Just libdir) $ do
    dflags &lt;- getSessionDynFlags
    setSessionDynFlags $ dflags { hscTarget = HscInterpreted
                                , ghcLink   = LinkInMemory
                                }
    setTargets =&lt;&lt; sequence [ guessTarget &quot;Test&quot; Nothing ]
    load LoadAllTargets
    -- Bringing the module into the context
    setContext [ IIDecl $ simpleImportDecl (mkModuleName &quot;Test&quot;)
               , IIDecl $ simpleImportDecl (mkModuleName &quot;Prelude&quot;)
               ]
    printExpr &quot;test&quot;
    printExpr &quot;test2&quot;
    

printExpr :: String -&gt; Ghc ()
printExpr expr = do
    liftIO $ putStrLn (&quot;-- Going to print &quot; ++ expr)
    act &lt;- unsafeCoerce &lt;$&gt; compileExpr (&quot;print (&quot; ++ expr ++ &quot;)&quot;)
    liftIO act
</code></pre>
<p>The output:</p>
<pre><code>$ ./Interp2
-- Going to print test
123
-- Going to print test2
target: panic! (the 'impossible' happened)
  (GHC version 7.6.3 for x86_64-apple-darwin):
	Not in scope: `test2'
Perhaps you meant `test' (imported from Test)

Please report this as a GHC bug:  http://www.haskell.org/ghc/reportabug
</code></pre>
<h1 id="error-handling">Error handling</h1>
<p>Our exercises above produced a number of GHC panics/erros. By default
you can expect GHC to spew all the errors onto your screen, but for
different purposes you might want to, e.g. log them.</p>
<p>Naturally at first I tried the exception handling mechanism:</p>
<pre><code class="language-haskell">-- Main.hs:
import GHC
import GHC.Paths
import MonadUtils
import Exception
import Panic
import Unsafe.Coerce
import System.IO.Unsafe
    
-- I thought this code would handle the exception
handleException :: (ExceptionMonad m, MonadIO m)
                   =&gt; m a -&gt; m (Either String a)
handleException m =
  ghandle (\(ex :: SomeException) -&gt; return (Left (show ex))) $
  handleGhcException (\ge -&gt; return (Left (showGhcException ge &quot;&quot;))) $
  flip gfinally (liftIO restoreHandlers) $
  m &gt;&gt;= return . Right
    
-- Initializations, needed if you want to compile code on the fly
initGhc :: Ghc ()
initGhc = do
  dfs &lt;- getSessionDynFlags
  setSessionDynFlags $ dfs { hscTarget = HscInterpreted
                           , ghcLink = LinkInMemory }
  return ()


-- main entry point
main = test &gt;&gt;= print
    
test :: IO (Either String Int)
test = handleException $ runGhc (Just libdir) $ do
  initGhc
  setTargets =&lt;&lt; sequence [ guessTarget &quot;file1.hs&quot; Nothing ]
  graph &lt;- depanal [] False
  loaded &lt;- load LoadAllTargets
  -- when (failed loaded) $ throw LoadingException
  setContext (map (IIModule . moduleName . ms_mod) graph)
  let expr = &quot;run&quot;
  res &lt;- unsafePerformIO . unsafeCoerce &lt;$&gt; compileExpr expr
  return res


-- file1.hs:
module Main where

main = return ()

run :: IO Int
run = do
  n &lt;- x
  return (n+1)
</code></pre>
<p>The problem is when I run the 'test' function above I receive the
following output:</p>
<pre><code>h&gt; test

test/file1.hs:4:10: Not in scope: `x'

Left &quot;Cannot add module Main to context: not a home module&quot;
it :: Either String Int
</code></pre>
<p>It appears that the exception handler did cat <em>an</em> error, but a
peculiar one, and not that one I wanted to catch.</p>
<h2 id="solution">Solution</h2>
<p>We've studied the GHC API together with Luite Stegeman and I think
we've found a more or less satisfactory solution.</p>
<p>Errors are handled using the
<a href="https://downloads.haskell.org/~ghc/latest/docs/html/libraries/ghc-7.10.2/DynFlags.html#t:LogAction">LogAction</a>
specified in the
<a href="https://downloads.haskell.org/~ghc/latest/docs/html/libraries/ghc-7.10.2/DynFlags.html#t:DynFlags">DynFlags</a>
for your GHC session. So to fix this you need to change 'log_action'
parameter in dynFlags. For example, you can do this:</p>
<pre><code class="language-haskell">initGhc = do
  ..
  ref &lt;- liftIO $ newIORef &quot;&quot;
  dfs &lt;- getSessionDynFlags
  setSessionDynFlags $ dfs { hscTarget  = HscInterpreted
                           , ghcLink    = LinkInMemory
                           , log_action = logHandler ref -- ^ this
                           }

-- LogAction == DynFlags -&gt; Severity -&gt; SrcSpan -&gt; PprStyle -&gt; MsgDoc -&gt; IO ()
logHandler :: IORef String -&gt; LogAction
logHandler ref dflags severity srcSpan style msg =
  case severity of
     SevError -&gt;  modifyIORef' ref (++ printDoc)
     SevFatal -&gt;  modifyIORef' ref (++ printDoc)
     _        -&gt;  return () -- ignore the rest
  where cntx = initSDocContext dflags style
        locMsg = mkLocMessage severity srcSpan msg
        printDoc = show (runSDoc locMsg cntx) 
</code></pre>
<h1 id="package-databases">Package databases</h1>
<p>A <em>package database</em> is a directory where the information about your
installed packages is stored. For each package registered in the
database there is a .conf file with the package details. The .conf
file contains the package description (just like in the .cabal file)
as well as path to binaries and a list of resolved dependencies:</p>
<pre><code>$ cat aeson-0.6.1.0.1-5a107a6c6642055d7d5f98c65284796a.conf
name: aeson
version: 0.6.1.0.1
id: aeson-0.6.1.0.1-5a107a6c6642055d7d5f98c65284796a
&lt;..snip..&gt;
import-dirs: /home/dan/.cabal/lib/aeson-0.6.1.0.1/ghc-7.7.20130722
library-dirs: /home/dan/.cabal/lib/aeson-0.6.1.0.1/ghc-7.7.20130722
&lt;..snip..&gt;
depends: attoparsec-0.10.4.0-acffb7126aca47a107cf7722d75f1f5e
         base-4.7.0.0-b67b4d8660168c197a2f385a9347434d
         blaze-builder-0.3.1.1-9fd49ac1608ca25e284a8ac6908d5148
         bytestring-0.10.3.0-66e3f5813c3dc8ef9647156d1743f0ef
&lt;..snip..&gt;
</code></pre>
<p>You can use <code>ghc-pkg</code> to manage installed packages on your system. For
example, to list all the packages you've installed run <code>ghc-pkg list</code>.
To list all the package databases that are automatically picked up by
<code>ghc-pkg</code> do the following:</p>
<pre><code>$ ghc-pkg nonexistentpkg
/home/dan/ghc/lib/ghc-7.7.20130722/package.conf.d
/home/dan/.ghc/i386-linux-7.7.20130722/package.conf.d
</code></pre>
<p>See <code>ghc-pkg --help</code> or the <a href="http://www.haskell.org/ghc/docs/latest/html/users_guide/packages.html#package-management">online documentation</a> for more details.</p>
<h2 id="adding-a-package-db">Adding a package db</h2>
<p>By default GHC knows only about two package databases: the global
package database (usually <code>/usr/lib/ghc-something/</code> on Linux) and the
user-specific database (usually <code>~/.ghc/lib</code>). In order to pick up a
package that resides in a different package database you have to
employ some tricks.</p>
<p>For some reason GHC API does not export an clear and easy-to-use
function that would allow you to do that, although the code we need is
present in the GHC sources.</p>
<p>The way this whole thing works is the following:</p>
<ol>
<li>
<p>GHC calls <a href="https://downloads.haskell.org/~ghc/latest/docs/html/libraries/ghc-7.10.2/Packages.html#v:initPackages">initPackages</a>,
which reads the database files and sets up the <a href="https://downloads.haskell.org/~ghc/latest/docs/html/libraries/ghc-7.10.2/Packages.html#t:PackageState">internal
table</a>
of package information</p>
</li>
<li>
<p>The reading of package databases is performed via the
<a href="https://downloads.haskell.org/~ghc/latest/docs/html/libraries/ghc-7.10.2/Packages.html#v:readPackageConfigs">readPackageConfigs</a>
function. It reads the user package database, the global package
database, the &quot;GHC_PACKAGE_PATH&quot; environment variable, and <em>applies
the extraPkgConfs function</em>, which is a dynflag and has the following
type: <code>extraPkgConfs :: [PkgConfRef] -&gt; [PkgConfRef]</code>
(<a href="https://downloads.haskell.org/~ghc/latest/docs/html/libraries/ghc-7.10.2/DynFlags.html#t:PkgConfRef">PkgConfRef</a>
is a type representing the package database). The <code>extraPkgConf</code> flag
is supposed to represent the <code>-package-db</code> command line option.</p>
</li>
<li>
<p>Once the database is parsed, the loaded packages are stored in the
<code>pkgDatabase</code> dynflag which is a list of <a href="https://downloads.haskell.org/~ghc/latest/docs/html/libraries/ghc-7.10.2/PackageConfig.html#t:PackageConfig">PackageConfig</a>s</p>
</li>
</ol>
<p>So, in order to add a package database to the current session we have
to simply modify the <code>extraPkgConfs</code> dynflag. Actually, there is
already a function <a href="https://downloads.haskell.org/~ghc/latest/docs/html/libraries/ghc-7.10.2/src/DynFlags.html#line-3656">present</a> in the GHC source that does exactly what we
need: <code>addPkgConfRef :: PkgConfRef -&gt; DynP ()</code>. Unfortunately it's not
exported so we can't use it in our own code. I rolled my own functions
that I am using in the interactive-diagrams project, feel free to copy
them:</p>
<pre><code class="language-haskell">-- | Add a package database to the Ghc monad
#if __GLASGOW_HASKELL_ &gt;= 707  
addPkgDb :: GhcMonad m =&gt; FilePath -&gt; m ()
#else
addPkgDb :: (MonadIO m, GhcMonad m) =&gt; FilePath -&gt; m ()
#endif
addPkgDb fp = do
  dfs &lt;- getSessionDynFlags
  let pkg  = PkgConfFile fp
  let dfs' = dfs { extraPkgConfs = (pkg:) . extraPkgConfs dfs }
  setSessionDynFlags dfs'
#if __GLASGOW_HASKELL_ &gt;= 707    
  _ &lt;- initPackages dfs'
#else
  _ &lt;- liftIO $ initPackages dfs'
#endif
  return ()
    
-- | Add a list of package databases to the Ghc monad
-- This should be equivalen to  
-- &gt; addPkgDbs ls = mapM_ addPkgDb ls
-- but it is actaully faster, because it does the package
-- reintialization after adding all the databases
#if __GLASGOW_HASKELL_ &gt;= 707      
addPkgDbs :: GhcMonad m =&gt; [FilePath] -&gt; m ()
#else
addPkgDbs :: (MonadIO m, GhcMonad m) =&gt; [FilePath] -&gt; m ()
#endif             
addPkgDbs fps = do 
  dfs &lt;- getSessionDynFlags
  let pkgs = map PkgConfFile fps
  let dfs' = dfs { extraPkgConfs = (pkgs ++) . extraPkgConfs dfs }
  setSessionDynFlags dfs'
#if __GLASGOW_HASKELL_ &gt;= 707
  _ &lt;- initPackages dfs'
#else
  _ &lt;- liftIO $ initPackages dfs'
#endif
  return ()
</code></pre>
<h2 id="links">Links</h2>
<ul>
<li><a href="https://downloads.haskell.org/~ghc/latest/docs/html/libraries/ghc-7.10.2/Packages.html">Packages</a> module,
contains other functions that modify/make use of <code>extraPkgConfs</code>
</li>
</ul>
  </div></content>
</entry>
</feed>