Search Results: "nomeata"

8 November 2009

Joachim Breitner: Parody song Another year at university

The list of parody songs on my web site just got a bit longer: I changed the text of Phil Collins Another day in paradise to Another year at university , about a girl failing a math test. It s not really funny, but the original wasn t either.

6 November 2009

Joachim Breitner: Releasing zpub as Free Software

Earlier this year, my brother and I developed a documentation management server for a small software developing company. They were sick of creating their documentation by sending around Word documents, having to manually merge them, losing changes and not getting a clean, consistent layout.So we created zpub for them: It is based on DocBook and Subversion, and adds a fairly nice web interface to it. Now their work flow is
  1. The editor checks out the DocBook source document via Subversion. With a client like TortoiseSVN, this is possible even for the less tech-savvy editor.
  2. He works on the document using the editor of his choice. We recommended an editor with a proper DocBook mode such as the XMLMind XML Editor or Serna Free, which was recently published as Free Software, to our customer.
  3. When satisfied, he commits his changes via Subversion, adding a comment describing his modifications.
  4. On the server, zpub renders the document in the various output formats (.html, .pdf, .chm), and makes the result available via the web interface. The commit messages are put there, and all previous revisions of the document can still be accessed.
  5. Optionally, an e-mail about the change is sent out to a per-document configurable list of recipients.
  6. Optionally, the documents are rendered with a DRAFT -Watermark on the pages, to avoid leaking wrong revisions to the outside. Only users with extended rights are allowed to release a document, thus causing a version without that watermark to be rendered.
For more details on the feature and usage of zpub, check out the documentation that you can find on the demo instance.We are actually quite satisfied by zpub, and it would be a petty if that was just it. Of course, there are quite a view programs out that that can provide these features plus many more, much more than a company the size of our customer would want to have (or even to worry about). So there is a niche between sending Word documents by mail and buying a very expensive, complicated product where zpub fits in.Being a fan of Free Software myself, and since zpub is based on Free Software, we decided that we want to release zpub itself under a Free License. We chose the EUPL, which is a GPL compatible license created by the European Commission, since our customer comes from a municipal environment. The code is hosted on gitorious now, so if you have a need for zpub, just give it a try.Also, if you run a Free Software project, manage your documentation in DocBook (or want to start to do so) and think that zpub might be a neat idea to allow more documentation writers to contribute, talk to me. I might well offer free hosting in that case. If you are a commercial user, I m still offering hosting (and support or feature development), just not for free any more. Note that the zpub user interface and documentation is currently only available in German.

3 November 2009

Joachim Breitner: Mimesweeper

Just the pun on the Windows game, no other deeper insights to be found here.

25 October 2009

Joachim Breitner: About the Freedoms of Web Services

For software, the question whether some software can be considered free is relatively easy to decide: Check the license of the code against the list of free licenses of your trust (the OSI list, the FSF list or the judgement applied by debian-legal) and that s (mostly) it. When it comes to web services in the broader sense, including hosters, communication providers, social networks etc., this are not so clear. In this blog entry, I ll try to list the various requirements that a service should fulfill and which I usually consider before deciding to use a service.The RequirementsA) Availability of source codeComing from the Free Software movement, this is the first requirement that comes to mind. If a web service claims to be free, then I want to be able to inspect how it is working, suggest and implement improvements and set up my own instance. For example, Canonical s software housing setup Launchpad was itself not Free Software until very recently. Having access to the source code is also the reason why I prefer gitorious over github for git hosting.B) Access to my dataDepending on the kind of service, it might hold data from me or about me that are important, such as my emails on a webmail service. If I won t have a way to easily retrieve my data to back it up or to move to a competitor, I ll think twice before trusting my data to this service.C) Free data formatsIf there is accessible data, it should be in a format that I can easily get and use with a choice of (Free) software. Not sure if such a service exists, but an online office suite only supporting its own proprietary file format (possibly with its own proprietary offline office suit) would be no option for me.D) An APIFor an extensively used service, I will want to have the possibility to optimize my user experience by automation. This requires that I can use the service not only in person, but also from tools I write. A very good example for this is Twitter: Besides registration, there is no need to use their web site at all and still use all the features, using the tools I find most fit for a task.E) Choice of providersCompetition is good. If a service is only provided by a single company, and I become dependent on the service, I become dependent on the company. A few years ago, SourceForge was mostly the only provider of gratis, comprehensive software project hosting. By now, there are a few alternatives, such as alioth, savannah or google code, which is appreciated. Note that when it comes to the proprietary instant messaging services (ICQ, yahoo messenger, MSN messenger), there is no choice of providers: To talk to my buddies on a certain network, I am bound to that provider. The same applies to social networks (Facebook, StudiVZ, XING), and is one of the reasons why I shun these yet. F) Federation between providersIf there is a choice of providers, and the service in question provides some kind of communication, it is very desirable if I can interact with users of the service on other providers. A very good example for this is e-mail: People @gmx.net can send mails to people @aol.com, and I can have @joachim-breitner.de and still communicate with everyone. This was not always the matter of course: Before Internet e-mail was common, people on AOL could not get in touch with people at CompuServe. These days, the problem persists with instant messaging (Jabber a.k.a. XMPP being the notable exception) and social networks. Also sites like gitorious or github could support federation if they would allow to create branches of repositories that are hosted elsewhere, allowing their users to use the familiar interface with all repositories they work with.Analysis of a few servicesSo far the theory. Let s see how various services fare.e-mailBeing from the old times of the Internet, when everything was better, it does not surprise that this passes all requirements: There is a large amount of Free e-mail servers and clients to choose from, my data is easily moved via well-known protocols such as POP or IMAP and save in standardized format. There is an abundance of service providers, and they all talk to each other. One could argue that the openness of email causes problems like spam, but I d say that this might be a design issue, but not inherent to the above criteria.Pretty much the same analysis applies to Jabber/XMPP.ICQI joined when I was young and unwise. Now I am stuck to AOL to keep in touch with a relevent part of my online correspondence. To use it on the operating system of my choice, other people had to reverse engineer the protocol and any time, AOL could change how its servers work and I ll be locked out. I can not get in touch with people on other networks, my buddy roster is not easily backed up and restored, and no, we can not see the source of the ICQ servers. I d wish I could switch over to Jabber completely, but there are always a few important people who do not use that yet.Github/GitoriousAlthough gitorious is slightly older, github managed to become more famous. These web sites allow developers to publish their source code and other contributors to easily branch, work on their changes, and propose them for merging in the main code. They are based on git, so I can get my data. There is a choice of providers. I am not sure how well I can access their functionality (merge requests etc.) programmatically. As said before, they do not interact well, and only gitorious has published its code.Facebook/StudiVZVery disappointing. I have heard that Facebook offers you a rich API, but otherwise, they fail every category. This is one of the reasons why I am not to be found on these networks yet.Twitter/identi.caTwitter, similar to Facebook, excels in the category API , but fails in the others. A better alternative is identi.ca: The software behind it is free, I can download contact data etc. It even supports federation via OpenMicroBlogging, although that did not break through yet it, it seems.OpenIDAnother very good example for what I want is OpenID, a service that allows websites to accept a user s credentials from another site. This saves the user from having to create accounts everywhere. There are free implementations, multiple providers, I can easily switch between them. A great feature of OpenID that goes a bit beyond federation is delegation: On the start page of my homepage http://www.joachim-breitner.de/, I saved who my OpenID provider is. Now I can use http://www.joachim-breitner.de/ as my OpenID, and even if I change my provider, this stays valid! This is a feature that not even XMPP easily provides.ConclusionWhether a web service is really free is a complicated question and has a graded answer. One has to balance the benefits of using a web service against the freedoms it is missing. I hope that in the long run, services fulfilling most or all of these requirements will prevail, so that I ll be networking socially and blogging microly with a good conscience.

11 October 2009

Joachim Breitner: arbtt: Now with Documentation

Yesterday I did what Free Software authors supposedly don t do. I wrote documentation. In fact, I had a relatively detailed README already, but I thought this would be a good opportunity to create a more elaborate documentation, using the ubiquitous DocBook. You can read the HTML documentation for arbtt online, where it s automatically updated when I push to the darcs repository. You can see, I use the same CSS file that most Haskell-related DocBook documentation seems to use.One motivation to use DocBook was that I can extract manpages from it, which should be present if I package arbtt for Debian. I was about to complain that references from the manpages to other part of the documentation can not work sensibly, but using the profiling feature of docbook-xsl, I can replace them by a textual reference to the user s manual if the file is processed for manpage output. Have a look at my changes for that if you want to know how it works.For some reason, the <refentry>-tags that make up the manpages are split to separate files when generating chunked HTML output, but they do not appear in the table of contents. You have to find a spot in the text where they are linked, as they are now in the section Program references , to find them. This is unfortunate, I expect that a few readers might miss this important part of the documentation. Am I doing something wrong?For the configuration file, I put an EBNF-style grammar description in the documentation. There is a special DocBook module for that, but I m not satisfied with it. On the right hand side of production rules, it has only special support for nonterminals, but no tags to semantically mark up choice, repetition etc. I followed the lead found at the YAML specification and put <quote>-Tags around literal parts of the grammar, but this is not valid according to the DocBook DTD. Speaking of the DTD: I guess since the EBNF-stuff is just a module, the tag <productionset> is not a valid content of <figure>. So, if I choose to use the EBNF module in a sensible way, I will not have a valid DocBook file.All in all, I am satisified with the result. Especially that nobody can say any more I like your program, but I can t contribute, because I don t know Haskell . Just improve the docs! :-)

4 October 2009

Joachim Breitner: arbtt goes Binary

Three weeks ago, I announced the automatic rule-based time tracker here, and it seems that there are actually users out there :-). Since then, it has recorded more than 240 hours of my computer s uptime in about 15000 samples. Until now, this data was stored in a simple text file, one line per entry, and relying on Haskell s Show/Read instances to do the serialization. Although not quite unexpected, this turned out to be a severe bottleneck: Already, it takes more than 25 seconds to parse the log file on my computer.Following an advice given to me on the #haskell IRC channel, I switched to a binary representation of the data, using the very nice Data.Binary module. The capture program will automatically detect if the log file is in the old format, move it away and convert the entries to binary data. And voil , the statistics program evalutes my data in about two seconds! This should be fast enough for quite a while, I hope.In my binary instances, which you can find in Data.hs, I prepended a version tag to each entry. This hopefully allows me to add more fields to the log file later, while still being able to parse the old data directly and without conversion. To still be able to manually inspect the recorded data, the program arbtt-dump was added to the package. The new version is uploaded to hackage as 0.3.0.One thing still worries me: With the old format, I could easily throw away unparseable lines in the log file (e.g. from a partial write) and still read the rest of it. With the new code, there is no such robustness: If the file breaks somewhere, it will be unreadable in its whole, or at least to the broken point. I m not sure what to do about that problem, but given the very low number of bytes written each time, I hope that it will just not happen.

14 September 2009

Joachim Breitner: Freaking out with LaTeX

If you want to play a trick on a colleague who is writing a LaTeX document: Open the file, copy the entire contents of the file and paste it at the very end. LaTeX will happily process the file and render the first part. But your colleague will likely try to edit the end of the file and soon feel haunted because his changes to the file have no effect no matter how often he deletes the resulting PDF file or any intermediate file, how often he renames the original file or moves it somewhere else...(Just happened to me, but not due to a mean colleague, but due to some accidential vim commands.)

13 September 2009

Joachim Breitner: The Automatic Rule-Based Time Tracker

A while ago, I thought: I seem to be less productive than I used to be. Why might that be? Do I spend more and more time with e-Mails? Or is it something else? I couldn t tell, so I needed a time tracking tool. There are a few of those for Linux that allow you, while working, specify what you are doing and then generate statistics about it. This approach has a few disadvantages:So I created arbtt, the Automatic Rule-Based Time Tracker. It comes with a background program that is started with your desktop session and will, each minute, record what windows are open, which one is active, what their titles and corresponding programs are. It also checks how long the user has been idle. No interaction required, no distraction possible. This information is stored in a log file. A separate tool allows the user to investigate this data. It is called rule-based because the mapping from the raw data to sensible tags that give information about the time sample is specified by a simple, but hopefully sufficiently powerful language.A simple example for a rule that indicates the currently used program would be:
tag Program:$current.program,
The prefix Program: is a category. Arbtt will ensure that for each time sample and category, at most one tag is specified. A more complex rule is
current window $title =~ m!(?:~ home/jojo)/projekte/(?:programming/(?:haskell/)?)?([^/)]*)!
==> tag Project:$1,
which makes use of the fact that both GVim and gnome-terminal display the full path to the currently edited file resp. to the working directory in the window title. This rule will track all my projects separately, and even automatically pick up new projects when they appear! You can see more rules in the example file.The statistics program then allows you to query the tags with some options:
Usage: arbtt-stats [OPTIONS...]
-h, -? --help show this help
-V --version show the version number
-x TAG --exclude=TAG ignore samples containing this tag
-o TAG --only=TAG only consider samples containing this tag
--also-inactive include samples with the tag "inactive"
-m PERC --min-percentage=PERC do not show tags with a percentage lower than PERC% (default: 1)
-i --information show general statistics about the data
-t --total-time show total time for each tag
-c CATEGORY --category=CATEGORY show statistics about category CATEGORY
For example, if I want to know what folders I have open while using evolution, I can run arbtt-stats -o Program:evolution -c Evo-Folder -m 3 to see this:
Statistics for category Evo-Folder
==================================
Time Percentage
=========================++======================
Evo-Folder:Eingang 22h20m00s 17.0%
Evo-Folder:Bekannte 16h40m00s 12.7%
Evo-Folder:d-haskell 9h40m00s 7.4%
Evo-Folder:Itomig 8h20m00s 6.4%
Evo-Folder:Verschickt 7h40m00s 5.8%
Evo-Folder:pkg-fso-maint 7h00m00s 5.3%
Evo-Folder:Bugs 6h00m00s 4.6%
Evo-Folder:planet debian 4h00m00s 3.0%
(60 entries omitted) 4h49m00s 36.7%
(unmatched time) 8m00s 1.0%
One big advantage of this approach is that you do not need to know in advance what queries you are interested in. Since the rules are applied when you are evaluating your data, and not when recording it, you can add more tags and forgotten special cases later.At this point, a big warning is due: This program will record a lot of very sensitive information about you. Be aware of this before you start using arbtt, and make sure you protect your data. You can get rid of all logs by deleting ~/.arbtt/capture.log.I have published arbtt on hackage. If you have cabal-install installed, you can install it with cabal install arbtt. See the README file for more information about setting it up. Depending on the feedback I get I will also consider packaging it for Debian.If you want to contribute, you are very welcome. The code is available at the darcs repository http://darcs.nomeata.de/arbtt/ (DarcsWeb). See the README for some ideas what to implement and feel free to come up with new ideas.

5 June 2009

Joachim Breitner: Third place in AI programming contest

My contribution to the programming contest held by the German FreiesMagazin got a third place out of 13 submissions. This is quite good, considering that I only wrote a small wrapper around the generic game-tree Haskell library by Colin Adams, and hardly gave any serious thought into the problem.All entires are available for download. I have annotated the table containing the results with the line count as given by ohcount:
W D L Points Language Code lines
1. Kroschinsky 904 242 54 2954 Python 589
2. Schulz 858 263 79 2837 Python 544
3. Breitner 837 281 82 2792 Haskell 264
4. Jackermeier 754 306 140 2568 Perl 183
5. Roth 574 338 288 2060 C++ 1731
6. Eitel 567 355 278 2056 Ruby 352
7. Reichel 342 328 530 1354 Python 266
8. Zimmermann 303 400 497 1309 Java 1070
9. Apensiv 190 353 657 923 Perl 410
10. Maraun 150 300 750 750 C++ 690
11. Golemo 131 319 750 712 Python 104
12. Ziegelwanger 120 337 743 697 C++ 868
13. Fuest 32 254 914 350 Python 645
Note that the line count for my haskell program includes the game-tree library, which I bundled in my submission. Without it, it s 156 lines of code I had to write, which is second best in the code golf category.If you look at the timing statistics, you will see that my program took the longest. When the contest was started, the timelimit was one minute per round which I of course tried to use as much as possibly, by increasing the search tree depth. Later into the contest, the rules were changed to limit it to one minute for a whole game, and that long-running programs will get points deducted. I did some minor changes based on a profiling run, but did otherwise not care too much about performance. I would have tried to improve the runtime by using Haskell s good ability for parallelization. But when I asked on what kind of machine the code will be run, but they would not tell me. They said that this is a hobby programmer s contest where allowing for parallelization were not fair, so I did not work in that direction.All in all it was a positive experience, showing of Haskell s qualities as a language that you can quickly get good results with.

2 June 2009

Joachim Breitner: Points of View

Thanks Behdad for pointing out this interesting advertisement campaign by HSBC. I m very surprised how a word, printed on top of an image, can completely reverse the impression that the image makes on you.
HSBC ad

22 April 2009

Joachim Breitner: Buzz free

My Openmoko FreeRunner suffered from the infamous hardware bug that causes bad buzzing for my dialog partner, making it relatively useless for me. Last week, though, a collegue of my brother fixed it for me (by applying some soldering-skills), and indeed, the audio quality is above bearable now! I plan to get Debian on the FreeRunner up to date again with the other developments in the community now. Or at least soon, depending on how much time I ll be able to spare.

3 April 2009

Joachim Breitner: Bejeweled AI in Haskell

The German online magazine FreiesMagazin has started a programming contest yesterday. The task is to write an AI for a two-player bejeweled-like game, where the stones that you can match cause your opponent to lose live points.This evening I thought that this would be a nice finger exercise in Haskell programming, and indeed it was. Most time was spent writing the code that communicates with the game supervisor (via text files) and that re-implements the game logic to simulate the next steps. The example code is in C++, so I had to do it again, but it s rather short: 123 lines, consisting of 8 lines for the module header, 26 lines for the data definitions, 16 lines for in- and output and 73 lines for the actual rules of the game.Writing the rest was really easy. 15 lines use a generic Haskell module to implement alpha-beta-search in Strategy.hs, and 6 lines of code to glue it all together. And I m sure one can do better...The program wins against the demo AI. By choosing other algorithms provided by game-tree might even improve that. Feel free to try it out!My code is available in a darcs repository (browse) under the GPL2 or later and I invite everyone to use it as a base for contest entries. If you want to use Haskell, you can just replace the Strategy.hs and do not have to re-implement the game logic. If you submit such a program, just make sure you credit me appropriately. Also, as always, patches are welcome. If the code is too slow for your taste, you can decrease the depth parameter in Strategy.hs.

17 March 2009

Joachim Breitner: Server updated to Lenny

Just updated my server from etch to lenny. It was a mostly painless procedure, only nagios needed some manual interaction, as it was upgraded from nagios2 to nagios3. My only bigger problem was an old web application (running my highschool s grad class and my old counter-strike clan s websites) written in mod_perl, which is not easily upgradeable, plus I did not want to use mod_perl again I ve had too much trouble with it eating up my memory or taking down the webserver.So I bit the bullet and replaced all mod_perl-related code with CGI-stuff. It actually went quite well, at least when accepting some hacks. Speed does not matter here, as the sites are there mostly for nostalgic reasons anyways.The other small thing that s lost with apache1 is the demonstration page for the Cross-Site-Authentication attack. Also not a great loss, and it can easily be re-implemented using a few lines of python and inetd.I wonder what to do with all the memory that was freed by not having apache1 (with mod_perl) and apache2 running at the same time :-)

11 March 2009

Joachim Breitner: In a Letter to Ghana s President

Thanks to Google s watchful eyes I found out that I was mentioned in a Letter to the President of Ghana, published pseudonymously on ghanaweb.com, that advocates Free Software to the new President of Ghana, John Atta-Mills. So, to all new presidents out there, if you need advice, just ask me :-)

15 February 2009

Philipp Kern: Lenny is done -- does anyone around Karlsruhe want to celebrate it?

Lenny got released yesterday and after having to push another update to Etch through volatile to fix an annoying warning when Lenny is in the sources.list, my work is now almost done too. (Yes, the autobuilding infrastructure is still offline, but we will get that reactivated shortly.) Anyway: if you live in or around Karlsruhe and did not get a mail by nomeata and me and if you would enjoy meeting tomorrow (Monday) evening, please speak up by mailing us. Let us celebrate the latest and greatest release. ;-) The plan is to meet up at the Vogelbr u at 19:30.

12 February 2009

Joachim Breitner: Reliability testing for python-dbus applications

In the Openmoko community, a lot of programs are written in python and use services provided over D-Bus. But I m under the impression that not enough programmers consider that D-Bus is a remote protocol, and the other side might fail to respond any time. The code then works find if nothing goes wrong, but does not handle problems well. Understandably, it is hard to get this error checking right if you can t really test it, as usually the D-Bus services do not fail. This is particularly annoying on a phone, because it might just be the program responsible for popping up the on screen keyboard that just failed.Therefore I started to write a little python module called python_test.py that replaces some D-Bus functions in the python bindings (SystemBus.get_object and Connection.call_blocking at the moment) and makes them fail with a certain probability. You can add "import dbus_test" to your program (and adjust $PYTHON_PATH) and run it a few times, to see which error conditions are caught and which cause your problem to fail. If you come across failures that the script does not yet generate, they can easily be added.Not sure yet if I am going to extend and maintain this, but I m open to suggestions and additions. Maybe this (or something similar) should be provided by python-dbus directly.

11 February 2009

Joachim Breitner: Openmoko User Meeting in Karlsruhe

About one hour ago we have finished the first Openmoko user meeting in Karlsruhe. Twelve FreeRunner (and Neo1973) owners have gatherd in the rooms of Entropia (the local CCC club), and discussed the various distributions, learned aboutt the FSO-alternative PyNeo, which was advocated by Josh, compared GPS applications and talked about various other projects and issues.
I collected some statistics about Distribution usage. Most common was SHR, with five users, followed by OM 2008.12 with three users. Single users had Debian, OM testing from pre 2008.12, PyNeo, EmDebian and OM 2008.9 installed. Only counting those who use their FreeRunner as their day-to-day phone, three are using SHR, one OM 2008.12 and one OM testing. I conclude that SHR seems to be a good choice if you want to have a working phone.Asked about their primary use case for the FreeRunner, almost all mentioned telephony and GPS. Half of the participants want to use it to browse the web, a little less think that games are important. Two people, who came from Stuttgart, see CellHunter as an important use caseConsidering that we filled three hours without running out of topics and the good feedback, we will likely have a sequel to this. A date has not been fixed yet, but will be discussed on the openmoko-community mailing list.BTW: I m still planning to package the SHR applications for Debian as soon as possible. Only one dependency (libetk) is missing, but according to Lutin from the pkg-e team, it s almost ready.

21 January 2009

Joachim Breitner: darcswatch uploaded to hackage

I just made my first upload to hackage (not counting uploads I did during my work in Dresden). Don Steward repeatedly told me to package and upload darcswatch, so I just did that. Thanks to Gwern Branwen to contribute the first cabal file.There is little documentation on how to set up darcswatch yourself, so if you actually want to try it out, you most likely will have to get in touch with me. Note that you can just use the installation on http://darcswatch.nomeata.de/.If you, for some reason, feel like hacking on darcswatch, I d be interested in memory reduction. I currently process 916 mails containing 1867 patches and 47MB, as well as 13 repositories, some of which are rather large, and the numbers are increasing.

31 December 2008

Joachim Breitner: Handling explicit and implicit recusion in Haskell data

For a while I have been pondering over a problem that arises when your functionally written program has some state with cross references for example a list of users, each of which uses a number of computers, and a list of computers, each having an owner. Implicit referencing For doing queries on such data, it would be convenient if every reference is just the referenced object itself. Although we would visualize this as a graph, semantically, it is more like an infinite tree. This is possible in Haskell, due to laziness, and if you create the data structure cleverly, it even uses constant memory, no matter how deep you enter this infinite tree (a recent post of mine talks about this). A possible data definition would be:
data User = User  
userName :: String,
uses :: [Computer]

data Computer = Computer
computerName :: String,
owner :: User -- references the Users

data State = State [User] [Computer]

testState = let user = User "Conrad" [computer]
computer = Computer "Z3" user
in State [user] [computer]
Explicit referencing But such a representation is very unsuitable for updates (at least I can t think if a nice way of updating such a graph without breaking the internal cross-references) and serialization, which is a must for a HAppS based application. So what one would probably start with is this data structure:
data User = User  
userId :: Int,
userName :: String,
uses :: [Int] -- references the Computers

data Computer = Computer
computerId :: Int,
computerName :: String,
owner :: Int -- references the Users

data State = State [User] [Computer]

testState = State
[User 0 "Conrad" [1]]
[Computer 1 "Z3" 0]
I think the semantics of this are clear. Note that the referencing is currently not type-safe, but this can be provided by phantom types. Maybe I ll write more about that later. Now imaging you want to display the information about the first computer with your web application. You extract the information with let State _ cs = testState in head cs and pass that to your templating engine. But what if your template wants to display the name of the owner? It only has access to his userId. You would either need to know what information the template will ever need, extract that from the state beforehand and pass it along, or give the template access to the whole state. In that case, though, there has to be lookup-logic in your output code, which is also not nice. Woudln t it be nice if you could, in your application logic, work with the explicit references, which are easy to modify and store, but somehow turn that into the implicit referencing? Duplicated representation One way would be to have two unrelated sets of data structures, ExplicitState, ExplicitUser, ExplicitComputer, which use explicit identifiers to reference each other, and ImplicitState,... which are defined as the first representation of our state. It is then mostly trivial to write a function that converts ExplicitState to ImplicitState. The big disadvantage of this is that you have to maintain these two different hierarchies. It also means that every function on the state has to be defined twice, which often almost identical code. Clearly, this is not desirable. Annotated representation It would be more elegant if the state is stored in one data type that, controlled by a type parameter, comes in the one or the other representation. To do that, we need two types: One that contains a value, and one that contains just a reference:
newtype Id v = Id v deriving (Show, Typeable, Data)
newtype Ref v = Ref Int deriving (Show, Typeable, Data)
Then we need to adjust our data definitions, to make use of these. (I ll leave out the names, to keep the code smaller)
data User ref = User  
userId :: Int,
uses :: [ref (Computer ref)]

data Computer ref = Computer
computerId :: Int,
owner :: ref (User ref)

data State ref = State [User ref] [Computer ref]
Here we introduce a type parameter ref , which will later be either Id or Ref. Note that now a reference also states the object it is a reference for, which greatly increases type safety. Functions on these data types that don t work with the references will be polymorphic in the ref type parameter, so only need to be written once. A User Id is a complete user with all related data, while User Ref is a user with only references. And a Ref (User Ref) is reference to a user, which contains references... Not so kind kinds Did you notice the lack of a deriving clause? Our data structures have the relatively peculiar kind ((* -> *) -> *), which makes it hard for the compiler to derive instances for things like Show. But we already know that we will only use Id or Ref for the type variable, so we can use ghc s StandaloneDeriving language extension and have these instances created:
deriving instance Show (User Id)
deriving instance Show (User Ref)
deriving instance Show (Computer Id)
deriving instance Show (Computer Ref)
deriving instance Show (State Id)
deriving instance Show (State Ref)
Toggling a type parameter The next step is to write the conversion function. It will have type
unrefState :: State Ref -> State Id
For that, and for later, we need lookup functions:
unrefUserRef :: State Id -> Ref (User Ref) -> Id (User Id)
unrefUserRef (State l _) (Ref i) = Id $ fromJust $
find (\u@(User i' _) -> i == i') l
unrefComputerRef :: State Id -> Ref (Computer Ref) -> Id (Computer Id)
unrefComputerRef (State _ l) (Ref i) = Id $ fromJust $
find (\u@(Computer i' _) -> i == i') l
These expect a State (with implicit referencing) and a reference, and look up this reference. The function unrefState then looks like this:
unrefState :: State Ref -> State Id
unrefState (State us cs) =
let unrefState = State (map (unrefUser unrefState) us)
(map (unrefComp unrefState) cs)
in unrefState
where unrefUser :: State Id -> User Ref -> User Id
unrefUser s (User i refs) = User i (map (unrefComputerRef s) refs)

unrefComp :: State Id -> Computer Ref -> Computer Id
unrefComp s (Computer i ref) = Computer i (unrefUserRef s ref)
Note how we tie the knot in the let expression. This is the trick that ensures constant memory consumption, because every reference points back to the same place in memory. Satisfied already? So what do we have? We have no duplication of data types, we can write general functions, and we can resolve the explicit referencing. We can also easily write functions like unrefUser :: State Ref -> User Ref -> User Id, which transform just a part of the state. But writing unrefState is very tedious when the State becomes more complex. Each of the other unrefSomething functions are very similar, but need to be written anyways. This is unsatisfactory. What we want, is a generic function, something like
gunref :: State Ref -> a Ref -> a Id
which, given a state with explicit references, replaces all explicit references in the first argument (which could be State Ref or User Ref or anything like that) with implicit ones. This function can not exist, because we would not know anything about a and b. But maybe we can do this:
gunref :: (Data (a Id), Data (a Ref)) =>  State Ref -> a Ref -> a Id
Typeable and Data Before being able to do so, we need to derive Data for our types. We can start with
deriving instance Data (User Id)
deriving instance Data (User Ref)
deriving instance Data (Computer Id)
deriving instance Data (Computer Ref)
deriving instance Data (State Id)
deriving instance Data (State Ref
but that will complain about missing Typeable instances. Unfortunately, ghc s deriver for Typeable (even the stand-alone-one), does not handle our peculiar kind, so we need to do it by hand. With some help from quicksilver on #haskell, I got it to work:
instance Typeable1 ref => Typeable (User ref) where
typeOf _ = mkTyConApp (mkTyCon "User") [typeOf1 (undefined :: ref ())]
instance Typeable1 ref => Typeable (Computer ref) where
typeOf _ = mkTyConApp (mkTyCon "Computer") [typeOf1 (undefined :: ref ())]
instance Typeable1 ref => Typeable (State ref) where
typeOf _ = mkTyConApp (mkTyCon "State") [typeOf1 (undefined :: ref ())]
everywhere is not enough Turning to the documentation of Data.Generics, I notice with some disappointment that there is no function that is able to change a type they all seem to replace a value by another value of the same type. But the functions gfoldl and gunfold sounded like they could be used for this. Warning: What comes now is a very non-haskellish hack that subverts the type system, just to get the job done. Please read it with a healthy portion of distrust. If you know of a cleaner way of doing that, please tell me! Wrapped Data I want to do some heavy type hackery, so I need to disable haskell s type system. There is Data.Dynamic, but not even that is enough, as we need to carry a type s Data instance around as well. So let s wrap that up:
data AData where AData :: Data a => a -> AData
instance Show AData where show (AData a) = "<" ++ show (typeOf a) ++ ">"

fromADataE :: forall b. Data b => AData -> b
fromADataE (AData d) = case cast d of
Just v -> v
Nothing -> error $ "Type error, trying to convert " ++
show (typeOf d) ++ " to " ++
show (typeOf (undefined :: b)) ++ "."
There is also a function that converts an AData back to a normal type, if possible. If it s not possible, then there is a bug in our code, so we give an informative error message. AData transformers Similar to everywhere, we want to have transformers that combinable. They need to have the change to convert an arbitrary value, but also signal that they could not convert something (and this something has to be recursed into). I came up with this:
type ADataT = AData -> Maybe AData

extADT :: forall a b. (Data a, Data b) => ADataT -> (a -> b) -> ADataT
extADT at t a@(AData v) = case cast v of
Just x -> Just (AData (t x))
Nothing -> at a

doNothing :: ADataT
doNothing = const Nothing
ADataT is the type for such a transformer. doNothing will not transform anything, and extADT can be used to add any function to the list of tried transformers, in the spirit of extT. The ugly part To apply such a transformer, I want to use this function, which I ll describe in the code comments:
everywhereADT :: forall a b. (Data a, Data b) => ADataT -> a -> b

-- first check if we can transform this value already
everywhereADT f v = case f (AData v) of
-- if so, coerce it to the users requested type, which hopefully goes well
Just r -> fromADataE r
-- if not, we need to recurse into the data structure
Nothing -> recursed

-- for that, we first need to figure out the arguments to the
-- constructor. We store them in the untyped list
where args :: [AData]
(Const args) = gfoldl k z v
-- gfoldl lets us have a look at each argument. We wrap it in AData
-- and append it to the list
k (Const args) arg = Const (AData arg : args)
z start = Const []

-- We need the data constructor of the input data type. If the user did not want
-- it to be transformed, it will be the same
c = toConstr v

-- To give better error messages, we make sure that the outmost type constructor
-- of the requested type actually has the data constructor we were given. Otherwise
-- gunfold will complain in a non-helpful way
input_type = dataTypeRep (constrType c)
output_type = dataTypeRep (dataTypeOf (undefined :: b))

recursed = if input_type /= output_type
then error $ "Can not convert <" ++ show input_type ++ ">"++
" to <" ++ show output_type ++ ">."
-- the types match, so we assemble the output type, using gunfold
else snd (gunfold k' z' c)
k' :: forall b r . Data b => ([AData], b -> r) -> ([AData],r)

-- we start by reversing the input list
z' start = (reverse args,start)

-- then we call us recursively on the argument and feed the result
-- to the output constructor
k' ((AData a) : args, append) = (args, append (everywhereADT f a))

-- Used for folding (we don t need to retain the original constructor)
data Const a b = Const a
What a beast! But surprisingly, it works. Here are some examples. Note that I always have to specify the requested output type:
bool2Int :: Bool -> Int
bool2Int False = 0
bool2Int True = 1

*Main> everywhereADT (doNothing extADT bool2Int) True :: Int
1
*Main> everywhereADT (doNothing extADT bool2Int) True :: ()
*** Exception: Type error, trying to convert Int to ().
*Main> everywhereADT (doNothing extADT bool2Int) (True,False) :: (Int,Int)
(1,0)
*Main> everywhereADT (doNothing extADT bool2Int) ([True,False],True,()) :: ([Int],Int,())
([1,0],1,())
*Main> everywhereADT (doNothing extADT bool2Int) ([True,False],True,()) :: [()]
*** Exception: Can not convert to .
*Main> everywhereADT (doNothing extADT bool2Int) [True] :: [Bool]
[*** Exception: Type error, trying to convert Int to Bool.
I hope this code does not inflict too much pain on any Haskell-loving reader. I know I violated the language, but I didn t know how to do it better (at least not without using Template Haskell). I also know that this is not very good performance wide: Every single value in the input will be deconstructed, type-compared several times and re-assembled. If that is an issue, then this function should only be used for prototyping. Almost done To apply this to our state, we only need to glue it to our lookup functions from above:
gunref :: (Data (a Id), Data (a Ref)) =>  State Ref -> a Ref -> a Id
gunref s w = let unrefState = gunref' unrefState s
in gunref' unrefState w

gunref' :: (Data (a Id), Data (a Ref)) => State Id -> a Ref -> a Id
gunref' unrefState = everywhereADT unref'
where unref' = doNothing extADT
unrefUserRef unrefState extADT
unrefComputerRef unrefState
Now we have a generic unreferencer. I set the type a bit more specific than necessary, to make it safe to use (under the assumption that the list of lookup functions is complete and will not leave any Ref in the output).
*Main> testState 
State [User userId = 0, uses = [Ref 1] ] [Computer computerId = 1, owner = Ref 0 ]
*Main> gunref testState testState
State [User userId = 0, uses = [Id (Computer computerId = 1, owner = Id (User userId = 0,
uses = [Id (Computer computerId = 1, owner = Id (User userId = 0, uses = ..
Oh, and by the way, if you want to test this code, you ll need at least:
 -# LANGUAGE DeriveDataTypeable, FlexibleInstances, GADTs,
FlexibleContexts, StandaloneDeriving, ScopedTypeVariables #-

28 December 2008

Joachim Breitner: MuMer relaunch preview online

A few years ago, I had some ideas about a real-world trading game. In short, a combination of the game play of Settlers of Catan , the cute pseudo-medieval world of The Settlers (the computer game), which you can play in your every day live along, without having to sit in front of the computer for a long time. I then started some code, lost motivation and let it sit there for a while.Recently, I re-developed interest in the idea and started from scratch, using Haskell and HAppS. To avoid losing interest again, I m now putting the code online and set up the server. I invite everyone to play around with it, maybe have a look at the code, send me patches or comments. As you can see, the web user interface is plain ugly HTML and could need some love. Some CSS is definitely needed, some AJAX would be nice. Also, the resource tree is very small at the moment there are a lot of things to work on, even if you don t want to touch Haskell!You can register at http://mumer.net/. You will be either given a forest (a source for wood) or a source of stone. You can reap your source, and trade on the Free Market , which is where you can always trade online, at bad prices. The idea is that you find real trade partners, to get better prices.For now, trading without physical contact is possible. You can create so-called issue ids, which represent stips of paper. You can then load resources on them, and give the paper (i.e. the number) to other players, who can then redeem them. Eventually, it is planned that these pieces of paper are provided centrally and (sufficiently) unforgeable, so that it is clear who owns a resource.You can also bid on certain stuff, such as a sawmil, which allows you to turn wood into boards. It will regularily be re-leased to the highest bidder.You can get the code (in a darcs repository) from http://darcs.nomeata.de/mumer2 and also browse the code.If you happen to be at the CCC right now and would like to talk about it, please do so!

Next.

Previous.