devNoo

musings of a Software Developer

Seven languages in seven weeks: My solutions for haskell day 1

| 0 comments

This are my solutions for the first Haskell chapter of the book seven languages in seven weeks.

I never touch Haskell, and only a bit of functional programming (mainly from this book), so I’m looking forward to have a look at Haskell, seen it is a functional languages that a lot of people refer to.

The first chapter shows the basics of the languages, so how to define functions, how lists work, how list comprehension works, tail recursion etc.

Exercise 1

The first exercise is quite a good start to look in to the possibilities of the language. The assignment is to create as many as possible different ways to implement an all even function.

Here is my go at it:

The first one is the example from the book. The next one uses list comprehensions to create a list with only the even numbers from the given list. The third solutions uses the filter function, to filter the list and only return the even numbers within the list.
The fourth one uses a fold right, to walk trough the list and do uses head:tail to append to the existing results.
The last one uses a fold left and concatenation on a list.
I’m really beginning to like the power of folds.

Exercise 2 : Reverse function

The exercise is to create a reverse list function. Quit straight forward with head/tail functions. I just would love that concatenation of tail:head would also be possible.

Exercise 3 : Color combinations

The exercise is to create a 2 tuple for every combination of the given colors, where the combination (x,y) is considered the same as (y,x) so only one of those should be included. I used a simple list comprehension:

Exercise 4: Multiplication tables

Create the multiplication tables from 1 to 12, in the form (factor, multiplier, result), using a list comprehension.

Exercise 5: State coloring

In the prolog chapter one of the first examples of prolog’s capabilities was to color states in a way no adjacent state had the same color. This exercise consists of doing the same in haskell.

Again I used a list comprehension, this time adding some constraints to it, so that the colors would be picked correctly.
It basically gives you all solutions for the problem

Conclusion

So far I did like Haskell, but we didn’t cover any real new stuff. Most off the functionality we used thus far was also available in clojure/erlang/scala. I’m looking forward to dive deeper in Haskell, but that will be after my visit of Devoxxx.

Leave a Reply

Required fields are marked *.

*