Monday, July 11, 2011

Starting Out In Haskell (Lists)

I'm going through a delightful introduction to the programming language Haskell called Learn You A Haskell For Greater Good.

So far I like it a lot.
I'm no expert programmer, but I have a few neat bits of Python in my pastebin, and have lost many hours of sleep tapping away in Python in a mildly addicted manner.

The great appeal for me is that I can read something in Haskell (at least basic stuff) without being confronted by a wall of punctuation and brackets.  It also differs from Python in that once you define a function:

doubleMe x = x +x

Then that function will never change.  You can rest assured a thousand lines later that "doubleMe 20" will return 40.

Haskell generates lists in a really neat way.

Let's say I want a list of all the integers between 1 and 1000:

Prelude> [1..100]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]

That's it.  Haskell's got it covered.

For my next trick, let's say I want a list of every second odd integer between 1 and 1000:

Prelude>[1,3..100]
[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99]

Neat, eh?

I thought, "OK, let's get crazy with this.  I want the difference between each integer on the list to be one greater than the previous difference, i.e...

1,3,6,10,15

And so forth.

So I tried:

Prelude> [1,3,6..100]

And got this error message:
:1:7: parse error on input `..'

I wonder how I can convey this in Haskell?  Oh well, something to look forward to.  For now, it's a lot of fun, but it's time for me to get to bed.

No comments:

Post a Comment