The featured image for an article on Haskell List Comprehension

Being able to manipulate lists is really important in any language.

Haskell isn’t as difficult as it may seem at first.

I think the majority of negativity towards this language comes from adjusting to it being a declarative language, not an object-oriented one.

Squaring All Integers in a Given Range (Single Generator)

You don’t need a function to do this. You can run this directly from your GHCi command screen.

The command [ x^2 | x <- [1..10] ] more or less translates to “x to the power of 2, for all x in the range 1 to 10.

The x <- [1..10] part is the generator. It generates values for x.

List Of Ordered Pairs (2 Generators)

The command [ (x,y) | x <- [1,2,3,4,5], y <- ["a","b","c"] ] uses two generators.

One for x, one for y; each has their own list.

It will return all combinations.

Joining a List of Lists (Dependant Generators)

You’ll notice in this function, the command [ x | xs <- xss, x <- xs ] is used.

This can be understood simply as:

  • a list containing “x”s
  • where the “xs”s are pulled from the input “xss”
  • and the “x”s are pulled from the “xs”s
Related:  Haskell Beginner Tutorial: Installing, First Program, Running, Basic Error Handling

This uses a dependant generator in that, we cannot get to x <- xs without getting xs <- xss first.

Get All Even Numbers in a Given Range (Uses a Guard)

If we want to find all even numbers in a given range we can do that. We’ll be using a generator of x , [1..n] which gives us a list of all numbers from 1 to n the input. However, we want to guard against the odd numbers, so we need to use x mod 2 == 0 so we’re only given numbers that divide by 2 and leave a remainder of .

The generator is guarded in this case by x mod 2 == 0.

Only when the guard is true, is the x generated and put into the list for returning.

Get List of Factors for a Given Number

This program is very similar to the “all even in range” example. We’re generating all x between 1 and (input) n, where n mod x is equal to 0.

The mod part is useful for determining whether something divides into something. If n mod x == 0 then it must be a factor. For example, 2 mod 4 would equal 0. However, 2 mod 5 would be equal to 1 because there is 1 remaining after the division.

This program works really well for this purpose. It returns the list of all factors for the given input n.

You can see in the above example that for each of the numbers [1,2,5,10] they are a factor of 10.