<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Posts on code | Brandon.Si(mmons)]]></title>
  <link href="http://brandon.si/./code/atom.xml" rel="self"/>
  <link href="http://brandon.si/"/>
  <updated>2012-02-01T22:04:23-05:00</updated>
  <id>http://brandon.si/</id>
  <author>
    <name><![CDATA[Brandon Simmons]]></name>
    <email><![CDATA[brandon.m.simmons@gmail.com]]></email>
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Haskell state of the Lens, etc.]]></title>
    <link href="http://brandon.si/code/haskell-state-of-the-lens/"/>
    <updated>2012-01-31T21:40:00-05:00</updated>
    <id>http://brandon.si/code/haskell-state-of-the-lens</id>
    <content type="html"><![CDATA[<p>For my own purposes, I wanted to take a tour of all the various formulations of
lenses on hackage and thought I would post the lightly-curated results here. I
just grepped the package list page for the following terms: lens, label,
record, accessor, editor, and reference.  Some were not sufficiently general to
include here.</p>

<p>Here were the ones implementing "lens-like" functionality, loosely in order of
my opinion on their usefulness for my own purposes:</p>

<ul>
<li><a href="http://hackage.haskell.org/package/fclabels">fclabels</a>: straightforward, lenses built on underlying <a href="http://hackage.haskell.org/packages/archive/fclabels/1.1.0.2/doc/html/Data-Label-Abstract.html#t:Point"><code>Point</code> type</a>, with support for lenses that can fail in <code>ArrowZero</code></li>
<li><a href="http://hackage.haskell.org/package/data-lens">data-lens</a>: uses natural <code>a -&gt; (s -&gt; a, s)</code> formulation for lens, leveraging category theory abstractions from the packages created after the breakup of Edward Kmett's <code>category-extras</code> (a.k.a. the Big Bang)</li>
<li><a href="http://hackage.haskell.org/package/partial-lens">partial-lens</a>: the above but suppporting failure on the container</li>
<li><a href="http://hackage.haskell.org/package/data-accessor">data-accessor</a>: package description has nice background, implementation (not exported, oddly) is same as Data.Lens, <a href="http://stackoverflow.com/a/5769285/176841">apparently</a> used to have wonky State monad implementation, seems from a similar school as "lenses" package</li>
<li><a href="http://hackage.haskell.org/package/state-record">state-record</a>: Lens type composed of simple setter/getter function pair, with TH generator and misc. functions for use with <code>State</code> monad</li>
<li><a href="http://hackage.haskell.org/package/lenses">lenses</a>: based on MonadState/StateT, odd formulation with no concrete type representation for the lens itself</li>
<li><a href="http://hackage.haskell.org/package/edit-lenses">edit-lenses</a>: implementation of ideas from this <a href="http://dmwit.com/papers/201107EL.pdf">paper</a> with demos <a href="http://hackage.haskell.org/package/edit-lenses-demo">here</a>, rather... involved</li>
<li><a href="http://hackage.haskell.org/package/pointless-lenses-0.0.7">pointless-lenses</a>: based on <a href="http://www.cis.upenn.edu/~bcpierce/papers/newlenses-popl.pdf">this</a> paper. also rather involved, for instance <a href="http://hackage.haskell.org/packages/archive/pointless-lenses/0.0.7/doc/html/src/Generics-Pointless-Lenses-Examples-Examples.html#preOrd_lns">here</a> is a <code>Lens (Tree a) [a]</code></li>
<li><a href="http://hackage.haskell.org/package/recursion-schemes">recursion-schemes</a>: another of EK's packages. there's allegedly a lens hiding here among the zygohistomorphic prepromorphisms (you think I'm joking)</li>
</ul>


<p>For an analysis of various approaches to lenses which don't necessarily have an
implementation on hackage, <a href="http://twanvl.nl/blog/news/2011-05-19-lenses-talk">these slides</a>
by Twan van Laarhoven were quite good, even without the accompanying talking
human. Conal Elliot's <a href="http://conal.net/blog/posts/semantic-editor-combinators">Semantic editor combinators</a>
pattern seems also relevant to mention here.</p>

<p>Here's a list of the <a href="http://packdeps.haskellers.com/reverse">reverse dependencies</a>
for these, as a guage of popularity/general usefulness:</p>

<table>
<tr><td>data-accessor</td> <td>46</td></tr>
<tr><td>fclabels</td> <td>33</td></tr>
<tr><td>data-lens</td> <td>12</td> </tr>
<tr><td>pointless-lenses</td> <td>3</td></tr>
<tr><td>recursion-schemes</td> <td>2</td></tr>
</table>


<h3>What about record-y packages?</h3>

<p>As a bonus, here are the packages which attempt to augment or improve on
records. I didn't spend much time trying to grok these:</p>

<ul>
<li><a href="http://hackage.haskell.org/package/ixset-1.0.2">ixset</a>: fancy indexable, groupable records gone wild</li>
<li><a href="http://hackage.haskell.org/package/records">records</a>: records as groupable name/value pairs, perhaps similar to ixset</li>
<li><a href="http://hackage.haskell.org/package/has">has</a>: entity-based records, looks novel but don't understand it after a quick look</li>
<li><a href="http://hackage.haskell.org/package/grapefruit-records-0.1.0.0">grapefruit-records</a>: record system for grapefruit FRP, haven't looked at implementation</li>
<li><a href="http://hackage.haskell.org/package/fields">fields</a>: high-level interface and cute syntax for record operations, built on fclabels, unmaintained</li>
<li><a href="http://hackage.haskell.org/package/setters">setters</a>: just generates "setter" functions for record fields using TH</li>
</ul>


<h2>My own thoughts</h2>

<p>The appeal of lenses for me is that they offer a first-class setter/getter on
which one can <a href="http://hackage.haskell.org/package/pez">build abstractions</a>
and more powerful libraries, not simply save the programmer some key strokes.
Lenses that simply throw an error when applied to the wrong constructor are not
suitable for this purpose.</p>

<p>IMHO the only package above that provides a straightforward lens type for real
algebraic data types is the seemingly unused 'partial-lens' variant on
Data.Lens. In which the simplified representation is:</p>

<pre><code>newtype Lens a b = Lens (a -&gt; Maybe (b -&gt; a, b))
</code></pre>

<p>The 'fclabels' package is great, but handles failure on <code>set</code> only w/r/t <em>both</em>
the outer value and the inner value to be set. This means we can perform
validation on a data type with its setter (cool!), but means we
cannot partially apply a lens and get back a pure setter <code>b -&gt; a</code> which is a
real problem for me.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[pez v0.1.0 released]]></title>
    <link href="http://brandon.si/code/pez-v0-dot-1-0-released/"/>
    <updated>2012-01-29T11:40:00-05:00</updated>
    <id>http://brandon.si/code/pez-v0-dot-1-0-released</id>
    <content type="html"><![CDATA[<p><a href="http://hackage.haskell.org/packages/archive/pez/0.1.0/doc/html/Data-Label-Zipper.html">pez</a>
is a powerful, generic zipper library that can be used with a minimum of
boilerplate, using <a href="http://hackage.haskell.org/package/fclabels">fclabels</a>
lenses as an interface. This new version supports fclabels 1.0 and uses the new
lenses supporting failure.</p>

<p>The API has changed significantly, but should be more stable at this point. You
can try it with a:</p>

<pre><code>$ cabal install pez
</code></pre>

<p>You can find the code on github <a href="https://github.com/jberryman/pez">here</a>. I
will try to post some fun examples here in the next week or two.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[simple-actors 0.1.0 released]]></title>
    <link href="http://brandon.si/code/simple-actors-0-1-0-released/"/>
    <updated>2011-10-11T14:02:50-04:00</updated>
    <id>http://brandon.si/code/simple-actors-0-1-0-released</id>
    <content type="html"><![CDATA[<p>Just a quick announcement of the release of
<a href="http://hackage.haskell.org/packages/archive/simple-actors/0.1.0/doc/html/Control-Concurrent-Actors.html">simple-actors</a>,
a DSL-style haskell
library for more structured concurrent programs via the
<a href="http://en.wikipedia.org/wiki/Actor_model">Actor Model</a>. You can fork it on
<a href="https://github.com/jberryman/simple-actors">github</a>, and install it via cabal
with a</p>

<pre><code>cabal install simple-actors
</code></pre>

<p>This version is significantly more coherent, powerful and simple than the
original 0.0.1 version (which was something I just whipped together for a blog
post I haven't gotten around to writing yet).</p>

<p>Let me know if you have any comments or suggestions!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A brief tutorial-introduction to 'fclabels' 1.0]]></title>
    <link href="http://brandon.si/code/a-brief-tutorial-introduction-to-fclabels-1-0/"/>
    <updated>2011-08-21T14:39:16-04:00</updated>
    <id>http://brandon.si/code/a-brief-tutorial-introduction-to-fclabels-1-0</id>
    <content type="html"><![CDATA[<p>Sebastiaan Visser et al. last week announced the release of v1.0 of
<a href="http://hackage.haskell.org/package/fclabels">fclabels</a>. This is a short
introduction to the changes for people who are already somewhat familiar with
the package.</p>

<blockquote><p><strong>Que?</strong> The fclabels package is a haskell library providing "first class
labels" for haskell data types and some Template Haskell code for
automatically generating said labels. This makes for a more composable and
much more powerful alternative to haskell's built-in record syntactic sugar.
<a href="http://blog.ezyang.com/2010/04/inessential-guide-to-fclabels/">Here</a> is a
good introductory tutorial.</p></blockquote>

<p>The new version features (besides some better names) a type for
<a href="http://hackage.haskell.org/packages/archive/fclabels/1.0.1/doc/html/Data-Label-Maybe.html">lenses that can fail</a>.
S.V. et al. added this functionality in a brilliant
and mostly (except for the name changes) backwards compatible way. We'll see
how it all works now.</p>

<p>We'll prepare a module for fclabels in the usual way:</p>

<pre><code>{-# LANGUAGE TemplateHaskell, TypeOperators #-}
import Control.Category
import Data.Label
import qualified Data.Label.Maybe as M
import Prelude hiding ((.), id)
</code></pre>

<p>The only odd thing above is our qualified import of <code>Data.Label.Maybe</code> which
provides getters, setters etc. that can fail.</p>

<p>We want to generate lenses for the following type, so we do the underdash
thing:</p>

<pre><code>data Example = X { _int :: Int , _char :: Char}
             | Y { _int :: Int , _example :: Example }
</code></pre>

<p>Notice how <code>_int</code> is a valid record for <em>both</em> constructors <code>X</code> and <code>Y</code>, where
the other two are partial functions.</p>

<p>Lastly, the usual splice for generating labels:</p>

<pre><code>$(mkLabels[''Example])
</code></pre>

<p>Let's load our file into GHCi and play a little:</p>

<pre><code>Prelude&gt; :l test.hs
[1 of 1] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main&gt; get int $ X 1 'a'
1
*Main&gt; M.get int $ X 1 'a'
Just 1
*Main&gt; M.get char $ X 1 'a'
Just 'a'
*Main&gt; M.get example $ X 1 'a'
Nothing
*Main&gt; get example $ X 1 'a'
:1:5:
    No instance for (Control.Arrow.ArrowZero (-&gt;))
      arising from a use of `example'
    Possible fix:
      add an instance declaration for (Control.Arrow.ArrowZero (-&gt;))
    In the first argument of `get', namely `example'
    In the expression: get example
    In the expression: get example $ X 1 'a'
</code></pre>

<p>Above we saw that:</p>

<ul>
<li><p>the total <code>int</code> label could be used in both <code>get</code> and <code>Data.Label.Maybe.get</code></p></li>
<li><p>M.get on our "partial lenses" (<code>example</code> and <code>char</code>) safely returned a Maybe value.</p></li>
<li><p>pure <code>get</code> used with partial lenses doesn't type check</p></li>
</ul>


<p>We need to look at some types (note I've cleaned up some of these type
signatures, yours may look uglier):</p>

<pre><code>*Main&gt; :t get
get :: (f :-&gt; a) -&gt; f -&gt; a
*Main&gt; :t M.get
M.get :: (f M.:~&gt; a) -&gt; f -&gt; Maybe a
*Main&gt; :info (:-&gt;)
type (:-&gt;) f a = Data.Label.Pure.PureLens f a
          -- Defined in Data.Label.Pure
*Main&gt; :info (M.:~&gt;)
type (M.:~&gt;) f a = Data.Label.Maybe.MaybeLens f a
          -- Defined in Data.Label.Maybe
</code></pre>

<p>You can see above that setters and getters are monomorphic. But how then were
we able to use <code>int</code> in both <code>get</code> and <code>M.get</code>? Time to look at the types of
our TH-generated lenses:</p>

<pre><code>*Main&gt; :t int
int
  :: Control.Arrow.Arrow (~&gt;) =&gt; Lens (~&gt;) Example Int
*Main&gt; :t char
char
  :: (Control.Arrow.ArrowZero (~&gt;),
      Control.Arrow.ArrowChoice (~&gt;)) =&gt;
     Lens (~&gt;) Example Char
*Main&gt; :t example
example
  :: (Control.Arrow.ArrowZero (~&gt;),
      Control.Arrow.ArrowChoice (~&gt;)) =&gt;
     Lens (~&gt;) Example Example
</code></pre>

<p>Whoah! Lenses themselves are polymorphic in the Arrow class; partial lenses
have additional restrictions of <code>ArrowZero</code> and <code>ArrowChoice</code> allowing for
failure and
<a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Arrow.html#t:ArrowChoice">choice</a>.</p>

<p>This is wizardry of the highest order.</p>

<p>Notice how we can still compose lenses freely, whether partial or total:</p>

<pre><code>*Main&gt; :t (.) (.) :: Category cat =&gt; cat b c -&gt; cat a b -&gt; cat a c 
*Main&gt; M.get (int . example) (Y 1 (X 2 'a')) Just 2
</code></pre>

<h2>A note on <code>mkLabelsNoTypes</code></h2>

<p>I had been using the noTypes variation to generate lenses that I was exporting
in a module, because the TH-assigned type sigs looked pretty nasty. If you do
this with >1.0 you will run into the monomorphism restriction and ambiguous
type variables.</p>

<p>Instead I would suggest defining <em>exported</em> lables by hand and giving them a
nicer looking (or monomorphic if you prefer) type sig.</p>

<p>You can even let fclabels generate the code and just paste it in, e.g.:</p>

<pre><code>Prelude&gt; :set -ddump-splices
Prelude&gt; :l test.hs
[1 of 1] Compiling Main             ( test.hs, interpreted )
test.hs:1:1: Splicing declarations
    mkLabels ['Example]
  ======&gt;
    test.hs:40:3-21
    char ::
      forall ~&gt;[a1kk]. (Control.Arrow.ArrowChoice ~&gt;[a1kk],
                        Control.Arrow.ArrowZero ~&gt;[a1kk]) =&gt;
      Lens ~&gt;[a1kk] Example Char
    {-# INLINE[0] CONLIKE char #-}
    char
      = let
          c[a1kl]
            = (Control.Arrow.zeroArrow Control.Arrow.||| Control.Arrow.returnA)
        in
          Data.Label.Abstract.lens
            (c[a1kl]
           . Control.Arrow.arr
               (\ p[a1km]
                  -&gt; case p[a1km] of {
                       X {} -&gt; Right (_char p[a1km])
                       _ -&gt; Left GHC.Unit.() }))
            (c[a1kl]
           . Control.Arrow.arr
               (\ (v[a1kn], p[a1ko])
                  -&gt; case p[a1ko] of {
                       X {} -&gt; Right (p[a1ko] {_char = v[a1kn]})
                       _ -&gt; Left GHC.Unit.() }))
</code></pre>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Module 'chan-split' released]]></title>
    <link href="http://brandon.si/code/module-chan-split-released/"/>
    <updated>2011-07-17T22:17:09-04:00</updated>
    <id>http://brandon.si/code/module-chan-split-released</id>
    <content type="html"><![CDATA[<h2>Whaa?</h2>

<p>chan-split is a haskell library that is a wrapper around
<a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Concurrent-Chan.html"><code>Control.Concurrent.Chan</code></a>s
that separates a Chan into a readable side and
a writable side.</p>

<p>We also provide two other modules: <code>Data.Cofunctor</code> (because there didn't seem
to be one anywhere), and <code>Control.Concurrent.Chan.Class</code>. The latter creates
two classes: <code>ReadableChan</code> and <code>WritableChan</code>, making the fundamental chan
functions polymorphic, and defining an instance for standard <code>Chan</code> as well as
<code>MVar</code> (an MVar is a singleton bounded channel, wanna fight about it?).</p>

<h2>Why?</h2>

<p>Having separate read/write sides makes it easier to reason about your code,
supports doing some cool things (defining <code>Functor</code> and <code>Cofunctor</code>
instances), and makes more sense (e.g. the function of
<a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Concurrent-Chan.html#t:dupChan">dupChan</a>
in the base library is much easier to
understand as an operation that happens on an <code>OutChan</code>).</p>

<p>Also I use it in (the coming new, less stupid version of) my module
<a href="http://hackage.haskell.org/package/simple-actors">simple-actors</a>.</p>

<h2>Where?</h2>

<p>You can get it with a:</p>

<pre><code>cabal install chan-split
</code></pre>

<p>And check out the <a href="http://hackage.haskell.org/package/chan-split">docs on hackage</a>.
Or check out the <a href="https://github.com/jberryman/chan-split">source on github</a>
and send me pull requests.</p>

<h1>Usage</h1>

<p>Let's write the numbers 1 - 10 to the InChan and read them as a stream in the
OutChan:</p>

<pre><code>module Main
    where

import Control.Concurrent.Chan.Split
import Control.Concurrent(forkIO)

main = do
    -- Instead of a single Chan, we initialize a pair of (InChan,OutChan)
    (inC,outC) &lt;- newSplitChan
    -- fork a writer on the InChan
    forkIO $ writeStuffTo inC [1..10]
    -- read from the OutChan in the main thread:
    getStuffOutOf outC &gt;&gt;=
        mapM_ print . take 10
</code></pre>

<p>And we'll make <code>writeStuffTo</code> and <code>getStuffOutOf</code>, simply be the standard
functions. Note that <code>writeListToChan</code> is actually polymorphic.</p>

<pre><code>writeStuffTo :: InChan Int -&gt; [Int] -&gt; IO ()
writeStuffTo = writeList2Chan

getStuffOutOf :: OutChan Int -&gt; IO [Int]
getStuffOutOf = getChanContents
</code></pre>

<p>Now I'll demonstrate the use of our Functor and Cofunctor instances by re-
defining those two functions above, after importing our Cofunctor class</p>

<pre><code>import Data.Cofunctor

...

-- we could convert the [Int] to [String] here but will instead demonstrate the
-- Cofmap instance:
writeStuffTo :: InChan String -&gt; [Int] -&gt; IO ()
writeStuffTo = writeList2Chan . cofmap show

-- likewise this demonstrates the Functor instance of OutChan:
getStuffOutOf :: OutChan String -&gt; IO [Int]
getStuffOutOf = getChanContents . fmap read
</code></pre>

<p>All right, leave your love or hate and stay tuned for the new (less stupider)
simple-actors lib.</p>
]]></content>
  </entry>
  
</feed>

