Mark Needham

Thoughts on Software Development

Haskell: Pattern matching a list

with one comment

As I mentioned in a post yesterday I’ve been converting a clustering algorithm into Haskell and I wanted to get the value from doing a bit wise or on two values in a list.

I forgot it was possible to pattern match on lists until I came across a post I wrote about 8 months ago where I’d done this so my initial code looked like this:

> import Data.Bits
> map (\pair -> (pair !! 0) .|. (pair !! 1)) [[1,2], [3,4]]

We can pattern match against the list like so:

> map (\(x:y:_) -> x .|. y) [[1,2], [3,4]]

Here x takes the first value, y takes the second value and the rest of the list is assigned to _ which we don’t use in this case.

There are loads of examples of pattern matching against different data structures in Learn You A Haskell and hopefully next time I’ll remember and won’t write hideous code like the first example!

Be Sociable, Share!

Written by Mark Needham

December 30th, 2012 at 10:39 pm

Posted in Haskell

Tagged with