Saturday, August 31, 2013

Exporting Data in Haskell Modules

Welcome to a straightforward and short blog post on how to export data in Haskell. When we speak of data, we mean types defined with the data keyword, and not type synonyms or any other related term. Typeclasses can also be exported in this way.

Exporting Data
For this example, let's define a simple data type, called Bit. Bit can hold either On or Off. The simple data declaration of bit is: data Bit = On | Off . In order to export this from our module, say, Binary.hs, we can either choose individual type constructors to export, or export them all by using the name of the Type followed by parenthesis and two dots.

To export just On: module Binary(Bit(On)) where

To export all of Bit's constructors: module Binary(Bit(On,Off)) where

To export all of Bit's constructors implicitly (The easy way, and what you will do 95% of the time): module Binary(Bit(..)) where

The (..) is basically saying "Export all of Bit's type constructors", which is good practice if you're using this type anywhere else.

Exporting Typeclasses
The same is true for Typeclasses. In exporting Typeclasses, you can choose individual Methods to export, or export them all with (..)

Friday, August 30, 2013

Scratching the surface of Emacs

Setting Emacs Up
This is an in-depth look at GNU/Emacs version 24.0, written in Emacs 24.0, and posted with Emacs 24.0. If you can't tell from that line alone, there is quite a bit to this monster of a text editor. Before it's possible to dive into specifics, it's important to understand the infrastructure that Emacs provides for extensions and customization, to see why it became the phenomena that it did.

Emacs is written in C at its core. However, it's fully extensible in a language called Emacs Lisp, which is a dialect of Scheme Lisp. One of the only functions of Emacs' core is to interprest this Emacs Lisp (abbreviated elisp) to create the user's text editing experience.

On a higher-level, the editor's "Prelude" supports various Modes. If you're editing C code, you're in c-mode (this can be invoked with the editor command M-x c-mode, where M is Alt). If you're editing Lisp, you will be in lisp-mode, etc. All of these mods and features can be invoked with the M-x command, which is basically a run dialog for the commands Emacs has at its core.

All of these modes are supplied via Elisp files, and before we can truly get started with Emacs we will want a package manager to install these little Elisp files. By default, Emacs has M-x package-install, which is what we will keep using, but it's recommended that you hook it up to the MELPA repositories. To do this, follow this quick 3-step guide here:

Now that you have Melpa installed, you'll have a much easier time installing modes and tools for the languages and workflow that you desire. The only extensions that I personally use are ghc-mod, haskell-mode, scion, and the Zenburn theme. Themes can be customized in your .emacs file, or from the graphical frontend from the Emacs menu bar (Options -> Customize Emacs -> Custom Themes).

Speaking of Options, before you even start editing text, it is a good time to run through and set all the options you want. Go through the options menu, tick what you like, untick what you don't, and when you're done click Options -> Save Options. I recommend Highlighting matching parenthesis, hiding the Tool Bar, showing Column, Lines, and Size, and using a monospace font.

Navigating Files
Unlike Vim, which is a modal editor, Emacs is always in editing mode. You can just start typing into a new file (which you make with C-x C-f, followed by the name of the file). This will write your text to the Emacs buffer, which can be flushed with C-x C-s. This will save the file you're working on. To navigate Emacs like you would vim, there are a certain set of keybindings every user should memorize (trust me, it's VERY hard at first, but more rewarding than the arrow keys once you get it down). The following key bindings are ordered by category. Remember that for the same modifier key, you don't have to lift your finger up.

C-p: Move one line up
C-n: Move one line down
C-a: Move to the beginning of the line
C-e: Move to the end of the line

M->: Move to the end of the buffer (Alt+Shift+Greater Than)
M-<: Move to the end of the buffer (Alt+Shift+Less Than)

C-f: Move one character forward
C-b: Move one character back

M-f: Move one word forward (a word is considered to start at punctuation or a space. Contiguous punctuation is considered one stop)
M-b: Move one word back

===Copying and Pasting
C-y: Copy selected text to the system clipboard
C-w: Cut
M-w: Paste
C-x h: Select all

===Killing and Deleting
C-d: Same as the delete key
C-k: Kill the line from the current point

===Editor functions
C-s: Search for text from the current point
C-g: Kill the M-x minibuffer

C-x o: Switch between Windows
C-x 2: Horizontally split window, making one new one.
C-x 3: Vertically split window, making one new one.
C-x 0: Kill the current window, but do not close the buffer.

===Buffers (think of these like open files, or tabs in Notepad++)
C-x (Arrow key left or right): Next or Previous buffer
C-x b: Select buffer by name (like everything in Emacs, supports tab completion)
C-x k

With these keyboard shortcuts, you will have solid usage ability within the Emacs editor. It will take a while to gain the muscle memory to learn these commands, but they're much worth learning. Many IDE's and Web Browsers (namely firefox) have support for these Emacs keybindings. You can also set what each key binding does yourself if you have a bone to pick with one of the defaults. Every keyboard command can also be accessed through M-x. M-x Tab will show a list of every command in the Emacs editor, so pull up a chair, and experiment with some of the ones that sound interesting.

Emacs offers a lot more than this simple tutorial covers. This is meant to cover the simple commands used in editing a file. However, Emacs can be made to be your IRC client, Email client, Web Browser, Git interface, Media Player, terminal... Whatever you want it to be, really. There have even been experimental  window managers for Emacs. Some of these functions are installed by default under the Tools menu, and can be accessed by way of M-x.

P.S: For a persistant text editing session, Emacs can be run as a server.

And, for whatever reason, if you want to close Emacs you can type C-x C-c.

Here is a small look at Emac's power:

How to Overload functions in Haskell

Haskell is a difficult language to get coming from imperative languages. In languages like C++ and Java, we can say this:

addOne(int x){ return x + 1;}
addOne(double x) { return x + 1.0;}

Here, addOne works on different types, but is still the same function name. This is called Overloading, and it's somewhat more difficult to do in Haskell. In order to overload functions, you will need to define a Typeclass (With the FlexibleInstances Program) to work on the types you want. You can indeed get this to work on generics.

To get this to work, we'll use an example. Think of the function "after". If you said after "profectium" 'f' , you would expect to get "ectium". The type signature for this function is after :: (Eq a) => [a] -> a -> [a]. However, there are cases where you may supply a list to the second argument of after, like in this example: after "profectium" "pro" in order to get the same output. This last example could be useful for sanitation purposes, and to avoid false positives.

The typeclass to get these two functions work will be called "Continuous". Here is the class definition: 

class Continuous list part where
  after :: list -> part -> list

In both instances of after, you take two arguments and return a sublist of a greater argument. So in order to become part of class Continuous, they have to satisfy an implementation of this function. To make out lives easier, we can use generics instead of individual types in our instance declarations. Everything that is part of the Eq typeclass will automatically qualify for class Continuous.

Here are some helper functions, ignore them if you're unconcerned with implementation specifics: 
sub :: (Eq a) => [a] -> Int -> [a]
sub [] _ = []
sub x 0 = x
sub (x:xs) c = sub xs (c - 1)

pos :: (Eq a) => [a] -> a -> Int
pos [] _ = 0
pos (x:xs) c
  | x == c = 0
  | otherwise = 1 + pos xs c

These will be used to define the after functions. The two headers for after are:

instance (Eq a) => Continuous [a] a
instance (Eq a) => Continuous [a] [a]

This is barring the implementations. Because of the requirements pos (and, by proxy, sub) to have the Eq typeclass, we constrain it in the instance declaration. We also set this up to work with Generics. This will now work. The full file text for the After library is as follows: 

{-# LANGUAGE FlexibleInstances     #-}
{-# LANGUAGE MultiParamTypeClasses #-}

module Cookbook.Continuous(
sub :: (Eq a) => [a] -> Int -> [a]
sub [] _ = []
sub x 0 = x
sub (x:xs) c = sub xs (c - 1)

pos :: (Eq a) => [a] -> a -> Int
pos [] _ = 0
pos (x:xs) c
  | x == c = 0
  | otherwise = 1 + pos xs c

class Continuous list part where
  after :: list -> part -> list

instance (Eq a) => Continuous [a] a where
  after x c = sub x (1+(pos x c))

instance (Eq a) => Continuous [a] [a] where
  after [] _ = []
  after x c
    | take (length c) x == c = sub x ((length c))
    | otherwise = after (tail x) c

Note the language pragmas at the top. They are required for this to work. Pragmas just enable features of ghc that are turned off by default.

Tuesday, August 27, 2013

How to stop xmobar from going below windows

If you are like me, you tried to use xmobar but whenever you open a window it falls below it. Or, worse yet, xmobar forces itself on TOP of the Windows you're trying to open. There are ways to change the behavior of xmobar by editing some Haskell code, but most people aren't comfortable doing that. There is a perfectly acceptable alternative (even if it is a hack) that I read from a forum somewhere that I now forget. Whoever originally discovered this, I thank you.

Fixing Xmobar with Trayer
There is a program called Trayer that will properly reserve the space for xmobar. Trayer is originally a system tray, but we will not being using it that way (we won't see trayer at all, actually). Install trayer and Install xmobar, then open up a file called

The text for the file should be as follows:

trayer --edge top --height 14 &
xmobar &

If your xmobar is configured to be on the bottom, then change --edge top to --edge bottom.

Make the file executable with chmod +x 

Lastly, copy the file to /usr/bin with sudo mv /usr/bin/xmobarF   

You can now properly launch xmobar by calling "xmobarF &" from the command line. 

My displaytrays:



How to change weather location in xmobar

Xmobar is the default bar of the xmonad Window Manager. It defaults to Glassgow, Scotland, as a little homage to the Glassgow Haskell Compiler, the compiler which xmonad was compiled in. However, for most users, Glassgow is not the city that we want to see displayed for our weather (if it is, you really did luck out with that one, huh?).

So, to change the location displayed, you just have to change four letters in you ~/.xmobarrc. You will see near the "commands" words "[ Run Weather "XXXX""

That four letter code is an ICAO code. The ICAO (International Civil Aviation Organization) provides information about where to look the weather up. Weather stations around the world use this as the standard for displaying local weather. Issue a google search for "ICAO [name of your town]" toget the code, and then replace the 4 letters between the quote with the ICAO you get. Restart xmobar, and the changes will take effect immediately.

To get my configuration, which defaults to Millville, New Jersey's airport, copy and paste this into a file in your home directory called .xmobarrc: (this is a good starting point if you don't have a file already, or you broke yours with hacks and tweaking)

Config { font = "-misc-fixed-*-*-*-*-10-*-*-*-*-*-*-*"
       , bgColor = "#0a0a0a"
       , fgColor = "#558e7d"
       , position = Bottom
       , lowerOnStart = False
       , commands = [ Run Weather "KMIV" ["-t","<station>: <tempF>F","-L","18","-H","25","--normal","green","--high","red","--low","lightblue"] 36000
                    , Run Network "eth0" ["-L","0","-H","32","--normal","green","--high","red"] 10
                    , Run Network "eth1" ["-L","0","-H","32","--normal","green","--high","red"] 10
                    , Run Cpu ["-L","3","-H","50","--normal","green","--high","red"] 10
                    , Run Memory ["-t","Mem: <usedratio>%"] 10
                    , Run Com "uname" ["-s","-r"] "" 36000
                    , Run Date "%a %b %_d %Y %H-> %l:%M:%S" "date" 10
       , sepChar = "%"
       , alignSep = "}{"
       , template = "%cpu% | %memory% | %eth0% - %eth1% }{ <fc=#ee9a00>%date%</fc>| %KMIV% | %uname%"

It is also available as a raw file on my github. These commands will install that file (ASSUMING YOU ARE IN YOUR HOME DIRECTORY):

rm .xmobarrc

If you aren't in your home directory, this will work.

rm ~/.xmobarrc
wget -o ~/.xmobarrc

How to get 12-hour clock in i3

At the beginning of our look into some neat tricks with i3, we are going to see how to get a 12 hour clock (with seconds) under i3. This assumes that you have the proper packages installed

  • i3-wm (sometimes called i3, either as a standalone or meta package)
  • i3status
  • i3bar
We are going to edit the global configuration file for i3status, a program that creates a status line for i3bar. The file is located over at /etc/i3status.conf, in case you know what you're doing and want to jump ahead of this article.

Open that file as root, and you should see something that looks like this:

Where it says time{format = "_"}, that is where the magic happens. The string supplied here is passed through a C function called strftime, which is the standard timestamp formatting tool across all Unix-like systems. The format they use with 24-hour clocks has the "%H" in the string. Find where it says "%H" inside of that string, and change it to "%l" to get the 12-hour time.

To see all of the options available, type "man strftime" at your terminal emulator.

 The format I use across all of my bars and time-tools is "%a %b %_d %Y %H-> %l:%M:%S", which comes across like this:

Friday, August 23, 2013

Higher-level scripting: bpp

If  you are like me, you make Bash or Zsh scripts to make your life easier with those small computing tasks. One of my favorite uses of Bash automation is the creation of Debian packages, which requires a LOT of work in directories. When you're typing in the waves of "mkdir" and "cd" into a bash script, it's easy to get lost, and that efficiency you felt while making the script goes out the window.

For the first time ever, there is now a solution: bpp. Bash PreProcessor reads a .bpp file, which is formatted plain text, and creates a bash script. The bpp language was designed with ease-of-use and visual perception in mind. How would you describe a directory layout to somebody through text? My answer to this question looked something like this:


I took this idea, and made a language with it. With the exception of Documents.txt, this is a valid bpp file that would create this directory layout, with proper nesting et al. Originally, this was as far as I was going to take the project. But I realized the need for creating content from within the script, so the next level of bpp was created. 4 special commands control the flow of a bpp file.

^file - Creates a file using touch

%command - Executes a shell command from the current directory

~file: line of text - Writes a line of text to a file.

} - Writes multiple lines to a file.

It is possible to do anything that Bash could with these commands. You can embed Bash scripts, or even embed Bash PreProcessor scripts with your PreProcessor scripts. This, paired with the directory layouts tool, creates a shell interface with an important feature: Modeling Power

A picture is worth a thousand words. A video is worth a lot more than that. Go watch bpp in action at the top of this article to see its capabilities. Since the making of this video, there has been the addition of one command, "jmp", which lets you jump between parts of the file like a goto statement.