Haskell 101

January 27, 2008

Checking for a value in a list

Filed under: Functional programming, Haskell, List comprehensions, Pattern matching, Ruby — Haskell 101 blogger @ 9:24 pm

Once we have a list, how do we check whether that list contains a certain value? This is sort of like the Ruby method “include?”.

We want to provide the value we are looking for, and the list in which we would like to look for it.

(1) includes::Int->[Int]->Bool

Let’s first try using pattern matching and recursion.

(2) includes x (y:ys)
      | x==y = True
      |otherwise = includes x ys

In other words, take the head of the provided list and compare it to the desired value. If equal, return true. We don’t need to look anymore, because we know the value is there. If not equal, then we need to keep looking, so recurse, using the tail of the provided list for the next evaluation.

(3) includes x [] = False

We will only get to this step if we have not matched the value before we get to the empty list. if that is the case, then we want to return False.

We’ll look next time at some other, perhaps more elegant, but perhaps slower, way to do this.

January 25, 2008

Welcome to Haskell 101

Filed under: Functional programming, Haskell, List comprehensions, Pattern matching, Ruby — Haskell 101 blogger @ 4:32 am

Welcome to Haskell 101, a blog where I will walk through my own learnings with the functional programming language known as Haskell. How did I decide to do this? Well, I like to program as a hobby. Of all the languages that I have programmed in (Java, PHP, Visual Basic, and Ruby), Ruby is by far the one I enjoy most. I started to read about the roots of the Ruby programming language and learned of its functional programming roots. I then started looking into the various functional programming languages out there (especially Erlang, Haskell, and Lisp). The one that for some reason drew most of my attention was Haskell. I love the concept of pattern matching, which is not related much at all to regular expressions, by the way. I also like the elegance of list comprehensions, which feel much like the power and succinctness of some Ruby structures, like

self.collect{|x|x.send(attr)}.uniq.sort

Welcome aboard!

Blog at WordPress.com.