# Solved: get count of item in list

Sure, let’s dive into it.

Programming is filled with many concerns and one of them is learning how to work with lists. **Lists** in Haskell are homogenous data structure that can store multiple items of the same type, making them suitable to solve a variety of problems. Today, We are going to discuss a simple yet useful operation on lists – calculating the count of an item.

In **Haskell**, we’ll be using some of the built-in functionality of this beautiful and efficient programming language.

```import Data.List (genericLength)
itemCount :: Eq a => a -> [a] -> Int
itemCount a = fromIntegral . genericLength . filter (== a)
```

## The Solution in Detail

The code snippet above uses a combination of Haskell tools, namely genericLength, filter, and equality operator. The function `itemCount` calculates the number of times an item occurs in a list.

The function `itemCount` takes two parameters: `a`, an element to be searched for and a list of elements `[a]`. The function then applies filter that forms a new list consisting of only elements for which the predicate `== a` is True. It’s then followed by using genericLength, a more general version of length function, which measures the length of the list to get the count of a particular item.

Here’s a sequence of execution:

1. The list is scanned and all instances of ‘a’ are extracted using filter.
2. The count is made of these instances using genericLength.

The solution uses standard **Haskell libraries and functions** such as genericLength and filter.

The `genericLength` function is part of the Data.List library in Haskell. It is a more generalized version of the regular length function because it can take a list of any type and return a number that represents the total count of items in the list.

The `filter` function, on the other hand, belongs to the prelude. It is a higher-order function that takes a predicate and a list and returns a list of elements which satisfy the predicate.

## The Use of ‘Eq’ in Haskell

In the code snippet, you will see that we specify Eq a in the function signature. The `Eq` is a typeclass in Haskell. It defines equality functions including `==` and `/=`, all types that want to use equality test should have an instance of this class.

Finally, positivity and elegance are at the heart of powerful code, similar to fashion. The strong similarities between, say, functional languages like Haskell, and high fashion are that they both provide us with tools and conventions to express ourselves, and that the languages we use shape the end result.

On that note, keep exploring, keep coding, and keep turning heads with your fantastic and unique code style, much akin to a showstopper on a fashion runway.

Related posts: