Haskell Notes 2

I found a good tutorial at Wikibooks, Haskell. It’s beginner level like these notes, but is way more organized. My notes here are more difficult to comprehend (due to lack of editing), but the examples are simple enough for some people to understand.

One thing I like about that book is that they start out without using type signatures. All the other tutorials use type signatures, even though they aren’t required. They’re really good form, but can get in the way of learning quickly.

Here’s an example that converts a list of strings into a JSON list of strings. (Sort of – I don’t know how to insert double quotes.)

jsonList lst = “[” ++ ( jsonListJoin lst ) ++ “]”
jsonListJoin [] = “”
jsonListJoin (x:[]) = “‘” ++ x ++ “‘”
jsonListJoin (x:xs) = “‘” ++ x ++ “‘,” ++ jsonListJoin xs

This defines three versions of jsonListJoin, and the correct one is dispatched by pattern matching. The first one never gets called normally, but it’s in there just in case.

The second version matches the end of the list, where you have one element followed by the null. It’s just like the final version except without a comma after this argument, and without the recursive call to jsonListJoin.

The third version is the most general version, and it matches any situation where there’s a list with two or more elements. The first item is taken and turned into a JSON string, and the remainder of the list is passed to jsonListJoin. There’s a comma in this version.