Seven Languages in Seven Weeks Part 11: Haskell Day 1
by Justin Michalicek on June 7, 2011, 7:08 a.m. UTCOn to Haskell! There were 5 exercises for day one. The first just really didn't interest me, the second, third, and fourth I did, and the fifth I started but didn't know where to go with it so there's only one solution.
The exercise I did was to write a function that takes a list and returns it reversed. This actually took longer than it should have. The logic is simple enough, but I didn't find anything that alluded to the correct syntax to append a single character to the end of a list for awhile. I only saw ++ in conjunction with strings, so I thought it was a string concatenation specific operator. The book only built lists using the colon syntax, which didn't work for what I was doing. One website showed some crazy syntax with lots of () involved to the point that it looked like lisp. In the end, here's what did the trick.
module Main where lreverse (h:[]) = [h] lreverse (h:t) = lreverse(t) ++ [h]
Just a simple recursive function that appends the head of a list to the tail of whatever a recursive call to the same function returns.
The next was to write a function that builds two-tuples with every combination of black, white, blue, yellow, and red. Duplicates with the same colors but in reverse order should not be included. This was really easy since this exact thing had been done with different data just a few paragraphs earlier. Just pass a list of those colors into the function below. It uses a list comprehension to loop over every combo in the list, basically like using an inner foreach, and ensures a < b so that the same combo but in reverse does not come up.
module Main where colors (x) = [(a,b) |a <- x, b <- x, a < b]
The next exercise was to write a list comprehension to build a multiplication table for 1-2 using three-tuples where the first two numbers are the numbers to multiply and the third is the result.
[(a, b, a * b) | a <- [1..12], b <- [1..12]]
The two exercises I didn't do were as follows, in case anyone cares. The first was to see how many ways I could write a function that takes a list and returns only the even numbers. I'm sure there was a way with list comprehension, fold, and probably some sort of recursive function. For some reason it just didn't interest me to figure out how to do it several ways. The other exercise was to implement the map coloring program from the Prolog chapter using Haskell.
The map coloring program took a list of several states and then set each one to red, green, or blue (I think those were the colors) where no states that border each other on the map would have the same color.