[UPDATE 2] So if you like this, you'll probably like the post where I integrate with an android app.
[UPDATE] I went a bit further, integrated the sucker with twitter.
So we used pi_piper just now to control some GPIO pins on our Raspberry Pi.
Good fun was had all around. It's also sitting in a 3d printed case because duh.
[UPDATE] I went a little further here and got Twitter involved.
This is just a release script I use on a private, largely-javascript project I work on regularly. Thought I'd share. It's an example of how great ruby can be for straight-up glue script.
begin
class VersionAlreadyTaggedError < StandardError; end
class UncommittedFilesError < StandardError; end
class UnstagedFilesError < StandardError; end
# Get VERSION file contents
version = File.read('VERSION').chomp
# Check to see if this version has already been tagged
exists = `git tag -l|grep v#{version}`.chomp != ""
if(exists)
raise VersionAlreadyTaggedError
end
# Check to see if there are any uncommitted files. No releasing with that sir!
uncommitted_files = `git status|grep "Changes to be committed"`.chomp != ""
if(uncommitted_files)
raise UncommittedFilesError
end
unstaged_files = `git status|grep "Changes not staged for commit"`.chomp != ""
if(unstaged_files)
raise UnstagedFilesError
end
# Merge development into master
STDOUT.puts "Merging development into master"
`git checkout master`
`git merge development`
`git push origin master`
# Tag this release and push it
version = "v#{version}" # We prefix versions with "v"
STDOUT.puts "Tagging version #{version}"
`git tag -a #{version} -m"Tagging version #{version}"`
STDOUT.puts "Pushing tags"
`git push origin --tags`
STDOUT.puts "Version #{version} has been released!"
# Check out development
STDOUT.puts "Checking out development branch"
`git checkout development`
# Error handling down below, if you hit one of these you weren't successful at
# releasing
rescue VersionAlreadyTaggedError
STDOUT.puts "This version has already been released. Please update the VERSION file, commit it, and try again."
rescue UncommittedFilesError
STDOUT.puts "There are some uncommitted files. Please check those in and try again."
rescue UnstagedFilesError
STDOUT.puts "There are some unstaged files. Please commit them or stash them and try again."
end
As developers, designers, and makers, we all come to rely on music during our daily activities to keep us focused. Beyond listening to music at work, I will have music going on my daily commute, when I'm jogging, or just in general when I'm around the house.
When I joined the team here at Isotope11, I was still purchasing a good deal of music, and was a bit apprehensive about the all you can eat music services.
The posse here, primarily uses Spotify, with a couple rogues in the bunch using Rdio or just straight up Pandora.
.. I went with the masses and signed up for Spotify.
Overall, I have been happy with the selection, but always felt it was a bit lacking in the stability of the OSX app (yes, I'm a happy Macbook Pro with retina owner). I also realized I was missing out on higher quality sources of music (I used to get everything as FLAC or ALAC). Spotify's high quality streaming option was a definite step in the right direction.
Well, after having decided to get some better headphones again, (better than my Yuin PK3 earbuds and better than my LG TONE bluetooth headphones), i realized that i'd be hampered by the source. As mentioned, Spotify DOES offer "high quality streaming", but not all of their catalog is sourced at 320kbit or even 256kbit (they up convert what isn't when you have the high quality streaming turned on).
i was going to try Rdio, but searching for certain tracks that exist on Spotify, they came up missing on Rdio, so i passed (sorry, Brandon, I tried!). Oh, and I couldn't find any definitive information about the quality of their streams.
Then i remembered Mog.
Now, I'll be honest, with Beats Audio buying Mog, it left me a bit concerned. The fact that Trent Reznor has a stake in Mog/Beats, for me, is the redeeming factor. Let's hope his discerning attitude towards music, music services, and technology in general, helps to drive the service in the right direction.
With that out of the way.. WHOA.. Mog sounds fantastic (yes, everything is sourced at 320kbit from the start).
Their catalog is vast, and easily keeps up with everything I had on Spotify (and then some).
They have mobile apps for iOS and Android, as well as desktop apps for Windows and OSX (nothing for Linux folk yet). On top of that, they have a full-featured HTML5 web app.
My music tastes range from Christian-centric hip-hop like Lecrae, Propoganda, Derek Minor, Thisl, Tedashii, Json, and Andy Mineo, to Christian-centric hard rock/metal like Demon Hunter, As I Lay Dying, Haste the Day, Underoath, Project 86, Oh, Sleeper, In Fear and Faith, and War of Ages all the way to triphop/downtempo like Massive Attack, Thievery Corporation, Zero7, Portisthead, Morcheeba, Peace Orchestra, The New Law, Kruder & Dorfmeister and Tosca.
Let's just say Mog easily hit all of the albums I'd expect them to have for each of those artists AND MORE (some obscure live albums and imports were also present). Spotify missed the mark on having Thievery Corporation's classic, Mirror Conspiracy, while Mog had it in full and glorious 320kbit (can't wait until we have bandwidth to stream full lossless sources).
Anyway, all of the services obviously have their positives and negatives. For now, I'm pretty convinced I'll drop Spotify and move forward with a long and fruitful aural relationship with Mog.
Let's get right to the awesome stuff:

- Javascript multithreading
- First off, let me say that the next two links came up because we found a performance bug in chrome (especially noticeable on mobile browsers) when there were in-flight ajax requests, wherein repaints would be broken up and the user perception would be hampered. We ended up fixing this particular application another way, but not before lots of fun research w/r/t javascript actors / multithreading happened :)
- Web Workers: Using jQuery Deferred
- webactors from MenTaLguY. Love that guy, anyone know what he's up to lately?
- alternativeTo - there was someone here who wasn't aware, thought I'd make sure everyone else knew about this site. Find alternatives to any software.
- webruby WebGL craziness - this is amazing. WebGL in a browser, running via mruby in javascript via emscripten. webruby has full access to dom/js libraries, from a ruby interpreter, running in javascript. We must play with this more.
- David got me hooked on Infinite, a game for android.
- JavaScript keyboard event handling made awesome - Seth sent this along, it looks neat. Haven't used it yet.
- Pixi.js looks like a really neat way to build cross-browser, mobile-friendly games in javascript. It's a fast, lightweight 2D library that works across all devices and uses WebGL where it can.
- Tim Berners-Lee sometimes posts things to the World Wide Web. He posted Axioms of Web architecture recently and it's definitely worth a read if you build the net.
- Javascript required reading
- The Breakpoint is apparently required watching. I've not yet watched 'em but I've seen it covered in a lot of places and I feel I'm doing myself a disservice. Seth recommends.
- Automatic Layout Bug Detection - can put it in your CI (beware is java)
- The ViziZicities Dev Diary is one of the better things you can read if you like visualizing data.
- Apparently Sails.js is "the future of API development." Looks like rails for JSON APIs on node. Seems nice-ish. Haven't touched yet.
- Adam pointed out a new firefox debug feature called Aggregate Repaint View
- Robby is learning AngularJS and so can you :) Oh crap here's another link about angular learning materials.
- Adam also showed us Puffing Billy for testing your javascript like you're using VCR to talk to an API.
- If you're on Ruby 1.8 and your tests are slow this might make them faster if you have the RAM for it
- This is a byte of data from David
- hastebin is an open source pastebin that's easy to use.
- @fogus wrote a Functional JavaScript book.
- Custom Shaders are really neat, works in chrome (on mobile too, though the demos are hard to use from a phone/touch device)
- Madeleine is object prevalence for ruby.
- Superherojs is a thing, if you want to learn js (you prolly do)
- showterm.io is a really cool thing Heath told us about, it lets you share terminal demos with people and they do all the things you'd want a terminal demo to do :)
- Adam told us about code school's Chrome DevTools course
- calm.com is pleasant
binding_of_callerlets you retrieve the binding of a method's caller in MRI 1.9.2+. This is howbetter_rails_errorsworks, and it's awesome. Bindings are something people should pay attention to.
Every now and then, I run across a gem that I end up using in nearly every project. As it turns out, several of the recent projects I have worked on have required some form of internal site content search engine. While there may be better options out there (like solr), I feel that this is the easiest way to add a search feature on your rails site using a postgres database. My main reason in trying out the postgres search gem (pg_search), was because it is extremely fast and on smaller projects I did not want to have a separate solr server running.
To install pg_search, just include the gem in your Gemfile:
gem 'pg_search'
When using pg_search, there are a multitude of options, but I will discuss the 2 main search features that I found helpful: multisearch and pg_search_scope. You can use one or both of these to get pg_search working, depending on your desired results.
multisearch
Multisearch is a single search command that when run will look at all models that have multisearch enabled and return an array of everything it finds as search objects, not the actual content object. The search objects that are returned in a multisearch include the "searchable_id" which is the actual object ID and "searchable_type" which is the object class name (ie. "Post"). From these bits of information, we can obviously look up the correct Post using its ID. This method of searching is nice because you can specify what attributes you would like to search for each model individually, so you have control over what fields are searched.
Before using multisearch you will want to run the generator to create a migration for the multisearch result documents.
rails g pg_search:migration:multisearch
rake db:migrate
Next you will want to attach pg_search to the model that you would like to search (we will do this in our Post model):
class Post < ActiveRecord::Base
attr_accessible :body, :title
include PgSearch
multisearchable :against => [:body, :title]
end
Thats is for multisearch, now just call the searcher and check out the results:
results = PgSearch.multisearch("foo")
pg_search_scope
Pg_search_scope is another method of searching that acts more like a model scope that you can call to get more specific results from a given model. With this method of searching, you will add a named search scope to the model and when called, it will return a list of the actual objects that if finds. You also have options to declare what attributes should be considered more relavent than others to order the results - for instance, place results with matches in the title ('A') higher than those with matches in the body ('B') of a post. This method can be used for more granular results, but will only return matches from the model that it is called on. You can also have multiple named pg_search_scope methods in the same model, as long as they have different names.
To setup a pg_search scope, add the following to your model:
class Post < ActiveRecord::Base
attr_accessible :body, :title
include PgSearch
pg_search_scope :custom_search,
:against => {
:title => 'A',
:body => 'B'
},
:using => {
:tsearch => {:prefix => true}
}
end
Thats is for pg_search_scope, now just call the searcher and check out the results:
results = Post.custom_search("foo")
Thats it!
You can now run searches in your app and focus on specific models with specific attributes as well as prioritize the results to suit your needs.
To find out more about the pg_search gem, check out the github page:
https://github.com/Casecommons/pg_search
HEYOOOOOO
- metriks lets you instrument ruby and gather metrics on your app. Saw it on the Ruby on Ales live stream.
- Digitizer is a 3D scanner being put out by Makerbot for use with their Replicators. Exciting times.
- Amazon's Mega Dropdown is well-designed.
- I hear that parade is good presentation software. Was forked from showoff from Scott Chacon, which is no longer maintained. That used to be the thing I liked, so this might become that thing :)
- Hey look! Unix tricks
- Ever wish you could write up a blog post about javascript that had a working example? Use examplify
- Here's an mruby interpreter running in a browser
- If you like reading about OO, here's the Wikipedia page on GRASP
- I need to find time to make sure I can add vim-obsession to my vimrc.
- I'm told that Tracelytics will be amazing when it's "Ready". It's in beta now, a newrelic-esque service.
- Here's a post on A simplified query interface for relationships in ActiveRecord 4. It fixes a thing I've long considered a bug in rails.
- Mike Perham tweeted about a performance monitor in 1 line of coffeescript
- Glimpse looks neat for rails apps. Github extracted it. It's awesome.
- Seth says this is good for when we have to customize bootstrap
- Here's a preview of qt5 for android
- There's VimDrills if you'r einto that sort of thing.
- If you use Bundler.setup instead of Bundler.require then you'll notice dependencies you weren't aware of. Seems smart.
- Jim Gay pointed out that you can search through your bundled gems for something easily because unix.
- Rapidash is a ruby gem to quickly build an api client upon.
- huginn is a system for building agents that perform automated tasks for you online. Think self-hosted IFTT.
- Seth says here's a decent breakdown of some of the basics for ember.js if you're into that sort of thing.
- Also this is the best thing ever
Also look a cat, courtesy of Brandon Adams
And David Chapman asked:


Table of Contents
Making Our Own Types and Typeclasses
Introduction ToC
About this tutorial
This is a concise tutorial based on the popular book from Miran Lipovača located at learnyouahaskell.com, thanks to him for permission to write this derivation. Minus the terminology, this tutorial assumes you will understand most everything up until the section on type signatures, and references are listed at the bottom of the page and linked to when detail might be useful.
What is Haskell
Haskell is a lazy, purely functional programming language with static and strong typing. Its code is often considered elegant, terse, and mind bending in a great way. Given that programmers can benefit from thinking about languages and the various methods for abstracting and combinining expressions, learning Haskell should be a beneficial exercise.
To get started, visit haskell.org/platform to download everything you need, or use a package manager of choice to grab the platform.
Starting Out
Interacting with the interpreter
GHCi is the interpreter which comes with the Haskell Platform. Just type ghci in a shell to get a feel for the language.
$ ghci
GHCi, version 7.4.1: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> 2 + 15
17
You can change the text before the prompt by typing in the following into the interpreter:
:set prompt "ghci> "
Let's add a number to a string!
ghci> 5 + "llama"
And the results: no llama for you!
No instance for (Num [Char])
arising from a use of `+' at <interactive>:1:0-9
Possible fix: add an instance declaration for (Num [Char])
In the expression: 5 + "llama"
In the definition of `it': it = 5 + "llama"
This error from the interpeter lets us know that the plus operator operates strictly on data types of Num (short for number).
Functions, lists, tuples, and ranges, oh my!
Here's our first function:
ghci> let doubleMe x = x + x
ghci> doubleMe 2
4
Lists in Haskell are a homogeneous data structure, i.e. they only store elements of the same type. Here's how you create a list:
ghci> let groceryList = ["pecans", "blueberries", "chocolate"]
ghci> groceryList
["pecans","blueberries","chocolate"]
ghci> let oneToTen = [1..10]
ghci> oneToTen
[1,2,3,4,5,6,7,8,9,10]
That last variable assignment demonstrates how to construct a list using a range. Creating a list of infinite length is easy with ranges:
ghci> let allNaturals = [0..]
ghci> allNaturals
[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21...
ghci> let allOdds = [1,3..]
ghci> allOdds
[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39...
These examples will execute forever unless you stop the process within GHCi using the command ctl-c. That last example is a demonstration of how to specify the step within a range.
Often we only want a subset of numbers from such a list, and Haskell provides several facilities for doing this. Common methods for operating on lists include:
ghci> head [5,4,3,2,1]
5
ghci> tail [5,4,3,2,1]
[4,3,2,1]
ghci> last [5,4,3,2,1]
1
ghci> init [5,4,3,2,1]
[5,4,3,2]
Hey look! A helpful list monster from LYAH:

A set comprehension using math notation looks like this:
This can be interpreted to represent a set that contains the first ten even, positivie natural numbers. The part before the pipe is called the output function, x is the variable, N is the input set and x <= 10 is the predicate. That means that the set contains the doubles of all natural numbers that satisfy the predicate.
Here's how we do the same thing in Haskell:
ghci> [x*2 | x <- [1..10]]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
To filter within a list comprehension, you use a predicate:
ghci> [x*2 | x <- [1..10], x*2 >= 12]
[12, 14, 16, 18, 20]
More examples of lists comprehensions at learnyouahaskell.com/starting-out#im-a-list-comprehenson
Like Standard ML, OCaml, and other languages in functional programming land, the _ symbol acts like a wildcard matching against any value.
ghci> sum [2,4,6] -- an example of the sum function which operates on lists
12
ghci> length [2,4,6] -- an example of the length function which also operates on lists
3
ghci> let length' xs = sum[1 | _ <- xs]
ghci> length' [2,4,6]
3
This custom length function, length', replaces every element of a list with 1 and then sums that up. This means that the resulting sum will be the length of our list. Also demonstrated in the examples is commenting. The -- operator tells
the compiler to not evaluate the characters pass this point until the
end of the line. If you want a multiline comment You would use the {-
and -} operators.
Tuples are like lists, but unlike lists, they may contain more than one type of value, i.e they are heterogenous. Also unlike lists, the type of a tuple is dependent on its length and the type of values it contains. Use tuples when you know in advance how many components some piece of data should have.
ghci> let a = (1, 'b')
ghci> :t a
a :: (Integer, Char)
Within GHCi, :t
instructs the interpeter to give us back the the type of the
following expression (in this case a) . You can get a list of
commands by entering :h at the prompt. The output we see here tells
us that the tuple contains just two elements, the first one being a
data type of Integer and the second element of type Char (short for
character). A string is really just a list of characters, and a string
has type [Char]. It is different than a single character, and it must
be enclosed by double quote marks, not single quotes. Other common
types include: Int, Integer, Float, Double, and Bool.
Types and Typeclasses ToC
Believe the type
Aye! Still following? Great! Because now we're getting to the fun stuff: types and typeclasses. Type classes first appeared in Haskell, and the concept really is not hard, let's go over some terminology.

Type annotations are what you put above your statements to let the compiler know how things should behave, for example:
first :: [a] -> a
first a = head a
That first line is the type annotation and it states that the following function takes a list as an argument and returns some value which is the same type that the list originally contained. Save the above to a file named something like head.hs, and then load it within GHCi like this:
ghci> :l head.hs -- given you are in the current dir of the file
Type annotations are very helpful in helping you to reason about how something should operate without requiring you to look at the statement's definition
An excerpt from the Haskell 2010 Report:
There are six kinds of names in Haskell: those for variables and constructors denote values; those for type variables, type constructors, and typeclasses refer to entities related to the type system; and module names refer to modules. There are two constraints on naming:
Names for variables and type variables are identifiers beginning with lowercase letters or underscore; the other four kinds of names are identifiers beginning with uppercase letters. An identifier must not be used as the name of a type constructor and a class in the same scope."
And a note from LYAH:
Note: the equality operator, == is a function. So are +, *, -, / and pretty much all operators. If a function is comprised only of special characters, it's considered an infix function by default. If we want to examine its type, pass it to another function or call it as a prefix function, we have to surround it in parentheses.
Given this information, let's look at the type signature of the plus symbol:
ghci> :t (+)
(+) :: Num a => a -> a -> a
And here's a graph breaking down the different parts of the type signature.

This states that the plus operator takes two values of
type Num and outputs another value with the same type. The :: operator can be read as "has type of". The class constraint
specifies the typeclass of the type variable a.
A typeclass is a sort of interface that defines some behavior. If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes.
Here are some common typeclasses:
- Eq defines equality,
==, and inequality,/=. - Ord is is used for ordering data.
- Show is used for making values into readable strings.
- Read is used for parsing of strings to produce values
- Enum specificies enumeration across a certain type
- Bounded is used to name upper and lower limits of a type.
- Num is what you think it is, a numeric type.
Syntax in functions ToC
A function may utilize pattern matching to define how it operates, and a function may contain several function bodies to match against. Here's an example of a function utilizing pattern matching:
lucky :: (Integral a) => a -> String
lucky 7 = "LUCKY NUMBER SEVEN!"
lucky x = "Sorry you're out of luck, pal"
-- save the above as lucky.hs and import it using :load lucky.hs
-- then type lucky 3 or lucky 7 to see how this operates
When you call lucky, its patterns are checked from top to bottom
and when a pattern matches, that function body is used.
This an example of a recursive factorial function using pattern matching:
factorial :: (Integral a) => a -> a
factorial 0 = 1
factorial n = n * factorial (n - 1)
Guards! Guards!
Haskell has if/then/else statements but guards are easier to read:
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| weight / height ^ 2 <= 18.5 = "You're underweight, you emo, you!"
| weight / height ^ 2 <= 25.0 = "You're supposedly normal, pffft."
| weight / height ^ 2 <= 30.0 = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
That can be read as:
when weight divided by height squared is less than or equal to 18.5 then output some text, otherwise when...
Let's check Miran's weight:
ghci> bmiTell 85 1.90
"You're supposedly normal, pffft."
We can make that function even more readable by using the where keyword at the end of the guards to assign variables:
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| bmi <= skinny = "You're underweight, you emo, you!"
| bmi <= normal = "You're supposedly normal, pffft."
| bmi <= fat = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
where bmi = weight / height ^ 2
skinny = 18.6
normal = 25.0
fat = 30.0
Case Expressions
I'm sure many of you are familiar with case syntax from other imperative languages. Haskell takes this concept perhaps a little further.
first :: [a] -> a
first xs = case xs of [] -> error "No head for empty lists!"
(x:_) -> x
This function acts just like our previous implementation of and returns the first element in the list or an error if the list is empty. Remember the _ symbol acts like a wildcard.
The syntax for case expressions is simple:
case expression of pattern -> result
pattern -> result
pattern -> result
...
expression is matched against a pattern, and if it matches, a result is returned.
Higher order functions ToC

At this point, LYAH covers currying, which shows that functions really only process one argument at a time, which might make for a nice transition to partial function application and passing functions around. This is skipped here, but if you're interested in learning about currying, see the wiki stub on haskell.org regarding currying. We will instead focus on functionas as first class citizens, i.e. functions as values that can be passed around to other functions.
Haskell functions can take functions a parameters and return functions as return values. A function that does this is called a higher order function. And since functions can be passed around as parameters to other functions, they are called first class citizens. Let's look at how the map function implements this:
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
map takes a function and a list and applies that function every element in the list, producing a new list. Let's see it in action:
ghci> map (+3) [1,5,3,1,6]
[4,8,6,4,9]
Function Application
When a compiler encounters the $ symbol, the expression on its right is applied as the parameter to the function on its left. So, given the statement:
sum (map sqrt [1..130))
We can rewrite it as:
sum $ map sqrt [1..130]
Function Composition
In mathematics, function composition is the application of one function to the results of another. -- Wikipedia article on function composition
Function composition in mathematical notation looks like:
(f ∘ g)(x) = f(g(x))
In Haskell, function composition is pretty much the same using the . function. The expression above looks like this:
(f . g ) x
And here's an example of function composition in practice:
ghci> map (sum . tail) [[1..5],[3..6],[1..7]]
[14,15,27]
Making Our Own Types and TypeClasses ToC

Any powerful programming language should be able to describe primitive data and primitive procedures and should have methods for combining and abstracting procedures and data. -- SICP
Algebraic data types intro
You are probably familiar with the types Bool, Int, Char, etc. Now it's time to create some of these data types ourselves. Here's how you create the Bool type:
data Bool = False | True
Simple enough, right? The different parts of the above statement identified:

The type constructor denotes the data type, and the data constructor (sometimes referred to as the value contructor within LYAH) specifies the different values that this type can have. The | is the or operator, so we can read this as: the Bool type can have a value of True or False. Note, both the type and data constructor are required to be capitalized.
Data constructors are actually functions that ultimatley return a value of a data type. Here's how we might represent a shape by contructing a new type Shape:
data Shape = Circle Float Float FLoat
Let's look at the type signature the Circle constructor:
ghci> :t Circle
Circle :: Float -> Float -> Float -> Shape
Here's how you might write a function which takes a shape and returns its surface:
surface :: Shape -> Float
surface (Circle _ _ r) = pi * r ^ 2
This states that the function takes a shape and returns a float. We couldn't write a type declaration of Circle -> Float because Circle is not a type, Shape, however is a type. And because we're interested in the radius, we don't actually care about the first two fields, which tell us where the circle is located on a Cartesion coordinate system. Let's see this in action:
ghci> surface $ Circle 10 20 10
314.15927
It works! If we try to just print out Circle 10 20 5 in the prompt though, we'll get an error. That's because Haskell doesn't know how to display our data type as a string, yet. When we try to print a value out in the prompt, Haskell first runs the show function to get the string representation of our value and then it prints that out to the terminal. To make our Shape type part of the Show typeclass, we modify it like this:
data Shape = Circle Float Float Float deriving (Show)
Now that that the type is part of the Show typeclass, we can do this in the interpreter:
ghci> Circle 10 20 5
Circle 10.0 20.0 5.0
Record Syntax
Let's make a data type which describes a person.
data Person = Person String String Int Float String String deriving (Show)
Do you know what the last string parameter is intended to represent? Ice cream. Yep. Our Person type holds the fields first name, last name, age, height, phone number, and favorite ice cream. Haskell has record syntax for making this information more obvious. Here's how that last example can be formatted using record syntax:
data Person = Person { firstname :: String
, lastName :: String
, age :: Int
, height :: Float
, phoneNumber :: String
, iceCream :: String
} deriving (Show)
By using record syntax, Haskell automatically made these functions from the data type: firstname, lastName, age, height, phoneNumber, and iceCream.
ghci> :t iceCream
flavor :: Person -> String
Type parameters
Not only can data constructors use parameters, but so can type constructors.
data Maybe a = Nothing | Just a
The type constructor here, Maybe, states that it takes one parameter, a, and it either returns Nothing or solely a.
Derived instances
A type can be made an "instance" of a typeclass if it supports the behavior. For example, the Int type is an instance of the Eq typeclass because the Eq typeclass defines behavior for stuff that can be equated. And because integers can be equated, Int is a part of the Eq typeclass. If a type is part of the Eq typeclass, we can use the == functions with values of that type. Consider this data type:
data Person = Person { firstName :: String
, lastName :: String
, age :: Int
}
If we have records for more than one person, it makes sense to see if they represent the same peson, which is why it makes sense for this type to be part of the Eq typeclass. So let's derive an instance:
data Person = Person { firstName :: String
, lastName :: String
, age :: Int
} deriving (Eq)
Now, let's test our Eq instance:
ghci> let mikeD = Person {firstName = "Michael", lastName = "Diamond", age = 43}
ghci> let adRock = Person {firstName = "Adam", lastName = "Horovitz", age = 41}
ghci> let mac = Person {firstName = "Adam", lastName = "Yauch", age = 44}
ghci> mac == adRock
False
ghci> mikeD == mikeD
True
ghci> adRock == Person {firstName = "Adam", lastName = "Horovitz", age = 41}
True
We can easily use algebraic data types to make enumerations, and the Enum and Bounded typeclasses help us with that. Consider the following data type:
data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday
Because all the data constructors are nullary (no parameters taken), we can make it part of the Enum typeclass. The Enum typeclass is for things that have predecessors and successors. We can also make it part of the Bounded typeclass, which is for things that have a lowest possible value and highest possible value. And while we're at it, let's also make it an instance of all the other derivable typeclasses and see what we can do with it.
data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday
deriving (Eq, Ord, Enum)
Because it's part of the Eq and Ord typeclasses, we can compare and equate days.
ghci> Saturday == Sunday
False
ghci> Saturday > Friday
True
It's also an instance of Enum, so we can get predecessors and successors of days and we can make list ranges from them!
ghci> succ Monday
Tuesday
ghci> pred Saturday
Friday
ghci> [Thursday .. Sunday]
[Thursday,Friday,Saturday,Sunday]
Input and Output ToC
A hello world program:
main = putStrLn "hello world!"
Put that in a file called helloworld.hs, and then compile it:
$ ghc --make helloworld
[1 of 1] Compiling Main ( helloworld.hs, helloworld.o )
Linking helloworld ...
And now to run it:
$ ./helloworld
hello world!
You can also run your program from the command line without having to compile:
$ runhaskell helloworld.hs`
hello world!
A common function used in I/O operations is putStrLn:
ghci> :t putStrLn
putStrLn :: String -> IO()
putStrLn takes a string and returns an I/O action which has a result type of an empty tuple. do syntax is used to glue several I/O actions together into one action to be performed. As an example:
main = do
putStrLn "Hi, what's your name?"
name <- getLine
putStrLn ("Hello " ++ name ++ ".")
++ is the concatenation operator for lists, requiring both lists to be of the same type. Note that a string is just a list of characters. The <- is for performing I/O actions and binding their results to names. Every line except the last line in a do block that doesn't bind can also be written with a bind.
Using return doesn't cause the I/O do block to end its execution. As an example, the following will cotinue executing through the return statement:
main = do
return ()
return "HAHAHA"
line <- getLine
return 4
putStrLine line
These return statements just encapsulate a result that is thrown away since it's not bound to a name. We use the <- function to bind stuff to names.
There are various functions mentioned in this section which are skipped, but one which will soon be needed is the getChar function which reads a character from input, and the 'putChar function which takes a character and returns an I/O action that will print it out to the terminal. Here's how you would use both:
main = do
c <- getChar -- grab user input
if c /= ' ' -- a space
then do
putChar c
else return ()
This is also the first time if/then/else notation has been shown, notice the indentation. This code exits its execution context with return () if it detects the input character is a space, otherwise it continues onward.
The when function is found in Control.Monad. We access it using import Control.Monad. The do block looks like a control flow statement, but it's actually a normal function. It takes a boolean value and an I/O action if that boolean value is True, and it returns the same I/O action that we supplied to it. However, if it's False, it returns the return () action, i.e. an I/O action that doesn't do anything. Here's how we can rewrite the previous piece of code by using when:
import Control.Monad
main = do
c <- getChar
when (c /= ' ') $ do
putChar c
Another handy function is the sequence function which takes a list of I/O actions and returns a single I/O action that will perform those actions in succession.
So, something like this:
main = do
a <- getLine
b <- getLine
c <- getLine
print [a,b,c]
can be rewritten to this:
main = do
rs <- sequence [getLine, getLine, getLine]
print rs
sequence [getLine, getLine, getLine] makes an I/O action that will perform getLine three times. print is something that is new, but it just prints to the screen as you expect.
Functors and Monoids ToC
Functors are things that can be mapped over, like lists, Maybes, and such. In Haskell, they're described by the typeclass Functor:
class Functor f where
fmap :: (a -> b) -> f a -> f b
class means we are defining a new typeclass. You can see that Functor has only one typeclass method, fmap. It takes a function, a -> b , which takes an a and returns a b . It then takes a box, f , with parameter(s) a inside it, and it returns a box, f with a b (or several of them) inside it.
The box analogy is used to help you get some intuition for how functors work, and later, we'll probably use the same analogy for monads. It's an okay analogy that helps people understand functors at first, just don't take it too literally, because for some functors the box analogy has to be stretched really thin to still hold some truth. A more correct term for what a functor is would be computational context. The context might be that the computation can have a value, or it might have failed, or that there might be more values (lists).
Lifting
If we write fmap :: (a -> b) -> (f a -> f b) , we can think of fmap not as a function that takes one function and a functor and returns a functor, but as a function that takes a function and returns a new function that's just like the old one, only it takes a functor as a parameter and returns a functor as the result. It takes an a -> b function and returns a function f a -> f b . This is called lifting a function. Let's play around with that idea:
ghci> :t fmap (*2)
fmap (*2) :: (Num a, Functor f) => f a -> f a
ghci> :t fmap (replicate 3)
fmap (replicate 3) :: (Functor f) => f a -> f [a]
You can think of fmap as either a function that takes a function and a functor and then maps that function over the functor, or you can think of it as a function that takes a function and lifts that function so that it operates on functors. Both views are correct and in Haskell, equivalent.
There are two functor laws that might seem a bit confusing and unnecessary, but if we know that a type obeys both laws, we can make certain assumptions about how it will act. If a type obeys the functor laws, we know that calling fmap on a value of that type will only map the function over it, nothing more. This leads to code that is more abstract and extensible, because we can use laws to reason about behaviors that any functor should have and make functions that operate reliably on any functor.
Functor Law 1:
- If we map the id function over a functor, the functor that we get back should be the same as the original functor.
Formally written:
fmap id = id
This says that if we do fmap id over a functor, it should be the same as just calling id on the functor:
ghci> fmap id [1..5]
[1,2,3,4,5]
ghci> id [1..5]
[1,2,3,4,5]
Functor Law 2:
- Composing two functions and then mapping the resulting function over a functor should be the same as first mapping one function over the functor and then mapping the other one. Formally written:
fmap (f . g) = fmap f . fmap g
If we do fmap (f . g) (Just x) , we see from the implementation that it's implemented as Just ((f . g) x) , which is of course, Just (f (g x)) . If we do fmap f (fmap g (Just x)) , we see from the implementation that fmap g (Just x) is Just (g x) . For that reason, fmap f (fmap g (Just x)) equals fmap f (Just (g x)) and from the implementation we see that this equals Just (f (g x)) .
If you think of functors as things that output values, you can think of mapping over functors as attaching a transformation to the output of the functor that changes the value. When we do fmap (+3) [1,2,3], we attach the transformation (+3) to the output of [1,2,3], so whenever we look at a number that the list outputs, (+3) will be applied to it.
Further reading at LYAH
Monoids
Monoids are simple algebraic data structures which have two properties:
- An an associative binary function
- an identity value with respect to the binary function
Here's its definition:
class Monoid a where
mempty :: a -- the identity
mappend :: a -> a -> a -- associative binary operator
Lists are monoids:
instance Monoid [a] where
mempty = []
mappend = (++)
Here's an example showing associativity using the ++ function:
ghci> "la" ++ ("di" ++ "da")
"ladida"
ghci> ("la" ++ "di") ++ "da"
"ladida"
And since mappend is equivalent to ++, we get the same associative functionality:
ghci> ("one" `mappend` "two") `mappend` "tree"
"onetwotree"
ghci> "one" `mappend` ("two" `mappend` "tree")
"onetwotree"
Further reading at LYAH
Monads ToC
With monads, we are concerned with this problem:
If you have a value with a context,
m a, how do you apply to it a function that takes a normalaand returns a value with a context? That is, how do you apply a function of typea -> m bto a value of typem a?
We are needing a bind function defined within the monad typeclass:
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
x >> y = x >>= \_ -> y
fail :: String -> m a
fail msg = error msg
We can take a normal value and wrap it inside a data type. For instance, we can take a 1 and wrap it so that it becomes a Just 1. Or we can make it into a [1], or an I/O action that does nothing and just yields 1. The function that does this is called pure. return is the same as pure, return doesn't change the state at all, it only serves to bring a value into the monad's context.
The bind operations, >> and >>=, combine two monadic values. We are specifically interested in the >>= function.
>>= takes a monadic value, and a function that takes a normal value and returns a monadic value and manages to apply that function to the monadic value. For the function to take a normal value, it has to take into account the context of that monadic value.
Maybe is also of type monad:
instance Monad Maybe where
return x = Just x
Nothing >>= f = Nothing
Just x >>= f = f x
fail _ = Nothing
Playing around with Maybe as a monad :
ghci> return "WHAT" :: Maybe String
Just "WHAT"
ghci> Just 9 >>= \x -> return (x*10)
Just 90
ghci> Nothing >>= \x -> return (x*10)
Nothing
"What monads and their associated operations provide is modularity. By defining an operation monadically, we can hide underlying machinery in a way that allows new features to be incorporated into the monad transparently." -A Gentle Intro to Haskell
That quote sums this section up, and there really isn't a replacement for Lipovača's chapters on Monads:
Both chapters are well worth the read.
Appendix A ToC
Concepts introduced in LYAH which were skipped
Chapter 6:
- let statements
- currying
- lambda functions
- partial function application
- folds
- tacit/point-free programming
Chapter 7:
- loading modules using the import statement
- playing around with the Data library
- exporting our modules.
Chapter 8
- type synonyms
- concrete types
- recursive data structures (and fixity)
- typeclass instances
- functors
- kinds
All of Chapter 10
Chapter 11
- Applicative functors
- newtype keyword
Chapter 12
- do notation
- The list monad
- monad laws
All of Chapter 14
Appendix B ToC
Related
Type safety

Cons (:) and nil ([])
- Mozilla XTags - IMO the most important link of the bunch. Web Components are the future dog.
- Postgres: The bits you haven't found
- AngularJS with Rails
- Icon Fonts
- volo is like a Gemfile for javascript projects in the browser. There's also JamJS
- rollbar is an exception notification service I heard about recently. Looks pretty good.
- Thinking in AngularJS
- Condi is conditional UI predicates for Rails.
- loader.io is a free service to load test your application.
- kadoh is a Distributed Hash Table in javascript in the browser. Useful for all the upcoming WebRTC in-browser P2P stuff that is surely coming.
- How do you spend your first five minutes on a server?
- Brandon sent us a link on How User Testing Improves a Design
- He also sent TechTV which seems like a great time sink :)
- Batsir is pipes and filters in Ruby. I'm working on something similar (though probably not as well thought-out) so this is lots of fun :)
- I sent out a link to EmberJS Videos
- (to which Seth responded with) AngularJS Videos
- Hyperion is a generic persistence API for Ruby.
yard server -m -G ./Gemfilewill let you browse documentation for your project's gems locally. via Sean McCleary- Your Rails Application Is Missing a Domain Controller
- View Inheritance in Rails, and new awesomeness in Cells
- Source Maps 101
Also here's a monkey doing pushups:

Some good links this week around Ruby OO-stuff. Tiny bit of front-end love.
- Getting live-reload working in linux
- coveralls.io is a continuously running code coverage tool. It has github and travis-ci integration. It's great for maintaining code coverage and increasing visibility into your code coverage.
- artoo.io is a microframework for robotics. Program your arduino (or something else) using a nice Ruby library.
- Bryan Helmkamp's refactoring-fat-models code samples repository is great to review if you want to avoid chunky models.
- This is a neat discussion of a repository pattern built to be friendly to Rails idioms
- I extracted a post from the Ruby Rogues Parley list into a gist. It's about experiments in object-oriented rails
- The HTML template tag is an exciting development. Chrome 26 is the only browser with support atm as far as I know.
- If you need to level up your front-end chops, this is a great 70-ish minute video walking through an entire front-end development process.
- The Deep Insights of Alan Kay is a fantastic article. If you don't love Alan Kay yet, read it.
- The Ruby Rogues this week had an interview with Ara T. Howard on Robust Ruby. It's fascinating. Best episode yet.
- Hobo is rails with more conventions. Not sure how I feel about it yet - played with it years and years ago when it was first coming out. Surprised it's still around.
- Developer Reaction Gifs. Just lol.
- ZURB Foundation 4 came out yesterday. I love Foundation because it is built atop
box-sizing: border-box. Also, the new release is mobile-first, which feels right for me philosophically. Progressive Enhancement trumps Graceful Degradation, and all that.
Great news! There's now a Ruby GEM for interacting with Google+'s OAuth2 endpoint. The GEM is omniauth-gplus
Setting it up
config/initializers/gplus_omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :gplus, ENV['GPLUS_KEY'], ENV['GPLUS_SECRET']
end
The gem will use the email scope by default, but you can get even more like so:
provider :gplus, ENV['GPLUS_KEY'], ENV['GPLUS_SECRET'], scope: 'email, profile'
Gemfile
gem 'omniauth-gplus'
