liveBook · Manning

Eta reduction

As explained in Learn Haskell by Example

An eta reduction is a transformation that removes a redundant parameter and its immediate application from a function definition.

Eta reduction removes a redundant parameter and its immediate application: an expression such as (\x -> f x) becomes f. Repeating this transformation lets function definitions omit trailing parameters and become more concise. section 4.2.1

The technique works naturally with partial application. Applying const to True produces a function that ignores its argument and returns True: const True has type b -> Bool. Removing the final parameter from numberAllLines is therefore valid because numberLines (const True) (const True) already has the required list-processing type. section 4.2.1

Concise line-numbering functions

The explicit definition numberAllLines text = numberLines (const True) (const True) text can be eta-reduced to numberAllLines = numberLines (const True) (const True). The same style produces variants that number every line, number only nonempty lines, or number and increment only nonempty lines. section 4.2.1 section 4.5

Listing 4.6 Three variants for functions that number lines based on different conditions
numberAllLines :: [String] -> NumberedLines
numberAllLines = numberLines (const True) (const True)    #1

numberNonEmptyLines :: [String] -> NumberedLines
numberNonEmptyLines =
  numberLines (const True) isNotEmpty              #2

numberAndIncrementNonEmptyLines :: [String] -> NumberedLines
numberAndIncrementNonEmptyLines =
  numberLines isNotEmpty isNotEmpty      #3

Compare three progressively specialized eta-reduced definitions and their use of partially applied predicates. section 4.2.1

How Learn Haskell by Example covers it

How deep it goes
Explains the lambda transformation, repeated reductions, and type justification, but stops short of formal semantics.
Examples
Demonstrates const True, numberAllLines, and line-numbering variants for all or nonempty lines.
What it assumes
Assumes familiarity with functions and arguments while explaining partial application and const in context.
What you can do after
Apply eta reduction to write concise Haskell function definitions after checking their resulting types.
How it connects
Connects eta reduction with partial function application, higher-order functions, lambda expressions, and type inference.

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.