liveBook · Manning

Function

As explained in Learn Haskell by Example

A function is a program construct that computes a result from supplied inputs according to its definition.

A function defines a transformation: it accepts input and evaluates to a result. In Haskell, functions are values, so a definition can be named, reused, and passed to other functions. Pure functions avoid side effects such as direct file, network, time, random-number, or memory access. section 1.2.2 section 2.2.3

Define and run a function

A named function can be written with an argument beside its name: square :: Int -> Int square x = x * x In GHCi, evaluating square 2 produces 4. The type Int -> Int reads as a function mapping an Int input to an Int result. section 2.1.2 section 2.2.3

Anonymous functions use lambda syntax. A multi-argument definition is shorthand for a function that takes one argument and produces another function, which is why add :: Int -> Int -> Int can be written as add x y = x + y. section 2.2.3

Use an argument instead of mutable state

A recursive function can model repeated work by receiving the changing value as a parameter. interactiveLines :: Int -> IO () takes a counter, prints a numbered input line, then calls interactiveLines (counter + 1). Its type is a function producing an IO action, not an IO action by itself. section 3.1.2

Figure 2.4 An example type expression for a function with its matching definition
figure

Compare a function type expression with its matching definition to see how input and result types correspond to parameters and the computed expression. section 2.2.3

How Learn Haskell by Example covers it

How deep it goes
Explains named and anonymous unary and binary definitions, function types, nested function results, and functions producing IO actions; defers monadic programming.
Examples
Uses square, add, and recursive interactiveLines for numbering entered lines.
What it assumes
Assumes no functional-programming experience and introduces Haskell syntax through REPL experimentation.
What you can do after
Apply it via GHCi to define, type, and run simple named or anonymous Haskell functions.
How it connects
Connects functions to immutability, pure functions, lambda abstractions, function types, recursion, and IO actions.

Also explained in

Compare how 20 books explain function →

Related concepts

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.