Search⌘ K
AI Features

Common Functions on Lists

Explore several important predefined functions for working with lists in Haskell. Understand how to check length and membership, append and access elements safely, extract sublists, and combine lists with zip. Gain practical knowledge of list operations essential for functional programming.

Before we dive deeper into writing functions on lists, let’s look at some of the most important predefined functions operating on lists. Here is a terminal running ghci, in which you can experiment with the various functions:

Terminal 1
Terminal
Loading...

Checking length

The length function returns the number of elements in a list of any type.

Prelude> length [2, 4, 4, 1]
4
Prelude> length []
0

Checking list membership

The elem function checks whether a value is contained in a list at least once, and returns a boolean answer. It works on all lists whose element types can be compared with ==.

Prelude> elem 1 [9, 2, 1]
True
Prelude> elem 4 [9, 2, 1]
False
Prelude> 2 `elem` [9, 2, 1] -- use as operator
True

Appending

...