Crea sito

How to Find length of a List in Haskell

Hi guys, in these weeks I’m studying Haskell and Functional Programming in general and since I’m finding this language very interesting and funny I want to share with you some tips and tricks on how to solve common problems.

In this post I want to show you how to find the length of a List in two ways:

  1. By using List Comprehension
  2. By using Pattern Matching

Ok we are ready to start!

1. By List Comprehension

length' :: (Num b) => [a] -> b 
length' [] = 0 
length' xs = sum [1 | _ <- xs]

This code means:

The function length’ will receive a List of any type and will return a number.

If the list is empty ([]) the length will be 0 and 0 will be printed.

If the list is non-empty, then for every element inside the list add a 1 to the sum of every element found.

 

2. By Pattern Matching

length'' :: (Num b) => [a] -> b
length'' [] = 0
length'' (_:xs) = 1 + length'' xs

This code means:

The function length’ will receive a List of any type and will return a number.

If the list is empty ([]) the length will be 0 and 0 will be printed.

If the list is non-empty, then separate the head (the first element) from the tail (all the other elements) and the sum 1 with the length of the sublist xs (that is the original list without the head).

 

Conclusion

I hope you find this post useful, for any comment or advice post a reply in the section below.

Remember that if you want to implement this function you have to obviously insert it inside a module and then import the module in the GhCi.