# Solved: anonymous function

Anonymous functions, commonly known as lambda functions, are an integral part of functional programming languages such as Haskell. Unlike traditional functions, anonymous functions don’t have a name. They are defined on the fly and typically used when a function is needed just once. Let’s dive into a problem that can be solved efficiently using anonymous functions.

## The Problem

Imagine you’re trying to analyse a list of words, and you need to statistically manipulate the data. You want to count the occurrences of each word length in the list. To make your code more succinct and easier to maintain, you decide to use anonymous functions.

## Solution with Anonymous Functions

import Data.List
import qualified Data.Map as Map

wordLengthCount :: [String] -> Map.Map Int Int
wordLengthCount = Map.fromListWith (+) . map (x -> (length x, 1))
[/pseudocode]

Let’s unpack the solution, step-by-step.

## Detailed Explanation of the Code

In the first line, we’re importing the necessary libraries. ‘Data.List’ provides list manipulation functions, while ‘Data.Map’ gives us access to a data type that can be used to implement a map data structure.

The function ‘wordLengthCount’ takes in a list of words (strings) as argument, and returns a Map that contains the occurrence count of each word length.

First, we’re using the map function to apply the anonymous function to each word in the list. Our anonymous function, or lambda function, is defined as:

x -> (length x, 1)
[/pseudocode]

The lambda function takes a word as input (‘x’), and outputs a tuple – the length of the word and 1. After this operation is applied to each word in the list, we end up with a list of tuples.

Next, we use the ‘Map.fromListWith’ function. The ‘fromListWith’ function is a handy function that takes a binary function and a list of tuples, and creates a map.

The binary function is (+), which adds up the second elements of the tuples if their first elements match. Thus, the function takes our list of tuples, groups them by word length and adds up the second elements of the tuples – essentially counting the occurrences of each word length.