I just read the first chapter of Programming in Haskell by Graham Hutton, afterwhich I watched the accompanying lecture by Erik Meijer on Channel 9. I then did the exercises from the end of the chapter. Here are my results.
Exercise 1 - Give another possible calculation for the result of double ( double 2 ).
double ( double 2 )
= { applying the outer double }
( double 2 ) + ( double 2 )
= { applying second double }
double 2 + ( 2 + 2 )
= { applying the first double }
2 + 2 + 2 + 2
= { applying plus }
8
This isn't in the official solutions document but I can't see how it's invalid. If I find out otherwise I'll update this post. For now I'm giving myself a mark for this exercise.
Correct
Exercise 2 - Show that sum [x] = x for any number x.
sum [ 3 ]
= { applying sum }
3 + ( sum [] )
= { applying sum }
3 + 0
= { applying plus }
3
I marked myself as correct for this as the working out is right however I did make a note to myself that, when proving something for x, the working out should use x. In my working out I have an assumed a that x is 3.
Correct
Exercise 3 - Define a function product that produces the product of a list of numbers, and show using your definition that product [ 2. 3. 4 ] = 24.
Part 1 - define product
product [ ] = 1
product [ x : xs ] = x * ( product xs )
Now I originally had product [ ] = 0, but realised quickly as I was doing my working out that anything multiplied by zero equals zero, and therefore the identity of multiplication is 1. Therefore the product of the empty list must be 1.
Part 2 - proof that product [ 2, 3, 4 ] = 24.
product [ 2, 3, 4 ]
= { applying product }
2 * ( product [ 3, 4 ] )
= { applying product }
2 * ( 3 * ( product [ 4 ] ) )
= { applying product }
2 * ( 3 * ( 4 * ( product [ ] ) ) )
= { applying product }
2 * ( 3 * ( 4 * 1 ) )
= { applying * }
24
Marked as Correct, but with the note that the identity of multiplication is 1.
Exercise 4 - How should the definition of the function qsort be changed so that it produces a reverse sorted version of the list?
I got this correct from a logic point of view, but I think my lecturer (if I had one) might have mentioned that did a bit more than was asked, I defined a new function rqsort (for reverse qsort) rather than just showing the change I would have made to qsort. Not incorrect but not exactly what was asked.
rqsort [ ] = [ ]
rqsort [ x : xs } = rqsort larger ++ [ x ] ++ rqsort smaller
where
smaller = [ a | a <- xs, a <= x ]
larger = [ b | b <- xs, b > x ]
Correct
Exercise 5 - What would be the effect of replacing <= by < in the definition of qsort?
The effect of replacing <= by < in the definition of qsort would be that any elements from the input list would only appear a single time in the resultant list. This is because we are removing the the logic that allows elements of equal value to the first element to be added to the resultant list.
Marked as Correct.
So that's five out of five for my first lesson, but with a few notes to take on board for next week.