[Haskell-cafe] List comprehension

Tillmann Rendel rendel at cs.au.dk
Tue May 5 11:36:12 EDT 2009


Hi,

applebiz89 wrote:
 > Hi, I think I need to use a list comprehension

There is no need to use list comprehensions, there is always a way to 
express the same thing without them. In fact, list comprehensions are 
defined as syntactic shorthands for this other way.

> filmsInGivenYear :: Int -> [Film] -> [String]
> filmsInGivenYear filmYear ?= [ title | year <- (Film title director year
> fans) , year == filmYear] 

Let's look at the type of your function. You have two arguments of types 
Int and [Film], so your definition should have two argument names:

   filmsInGivenYear filmYear films
     = ...

Now, we want to look at each of the films

   filmsInGivenYear filmYear films
     = [ ... | film <- films ... ]

The part "film <- films" means: Look at each element of films in turn, 
and name the current one film.

But we actually want to look inside the film (we want to check the year).

   filmsInGivenYear filmYear films
     = [ ... | Film title director year fans <- films ...]

This means to look at each of the films in turn, and match the current 
film against the pattern (Film title director year fans). So if the 
current film has been created by a call like (Film ...), we will get the 
various data fields in the variables title, directory, year and fans.

Now we want to check that the year is correct.

   filmsInGivenYear filmYear films
     = [ ... | Film title director year fans <- films, filmYear == year]

The part (filmYear == year) means that we are only interested in such 
films where year is filmYear.

Finally, we want to return the name of the remaining films.

   filmsInGivenYear filmYear films
     = [title | Film title director year fans <- films, filmYear == year]

Hope that helps,
   Tillmann

PS. I'm not a native speaker, but shouldn't it be "movies" and not "films"?


More information about the Haskell-Cafe mailing list