Chuyển đến nội dung

Bài 15 · Functions

Lambdas, Composition and the $ Operator

Learn Haskell lambda syntax, the composition operator (.), the application operator ($), flip and how to build readable function pipelines.

Small functions are the building blocks of Haskell programs, and three tools make them easy to combine: lambdas (functions without names), the composition operator (.), and the application operator ($). Together they let you write code as a pipeline of steps, reading nearly like a sentence.

You will use these constantly with map, filter and folds and with the partial application ideas from Currying and Partial Application. Real Haskell is read-only here; the runnable blocks are JavaScript stand-ins that say what they imitate.

Lambdas

A lambda expression is an anonymous function. The backslash stands in for the Greek letter lambda:

HASKELL
\x -> x + 1
\x y -> x * y
\(a, b) -> a + b

The parameters come after the backslash, then an arrow, then the body. A lambda can pattern match on a single constructor or tuple as above, but it cannot have several clauses. For multiple cases use case, or the LambdaCase extension, or a named function.

Lambdas are handy when a function is used once:

HASKELL
map (\n -> n * n + 1) [1, 2, 3]       -- [2,5,10]
filter (\(name, age) -> age >= 18) people

Often a section does the same job more briefly: (+ 1) instead of \x -> x + 1. Choose whichever reads better. If a lambda grows past one short line, give it a name with a where binding (see Guards, where and let).

Defining f x y = x + y is just sugar for f = \x -> \y -> x + y. Lambdas and named functions are the same thing underneath.

The $ operator

($) is function application with the lowest possible precedence and right associativity:

HASKELL
($) :: (a -> b) -> a -> b
f $ x = f x

That looks useless, but ordinary application binds tighter than any operator, while $ binds looser than all of them. So $ lets you drop parentheses:

HASKELL
print (sum (map (* 2) [1, 2, 3]))
print $ sum $ map (* 2) [1, 2, 3]

Everything to the right of a $ is evaluated as one argument for the function on its left. Both lines print 12.

Two cautions. First, do not overuse it: f $ g $ h $ x is usually better written with composition. Second, remember it cannot swallow an operator expression's own structure: f $ x + 1 means f (x + 1), which is what you want, but f x + 1 means (f x) + 1.

$ can also be passed around as a function, for example to apply a list of functions to one value:

HASKELL
map ($ 3) [(+ 1), (* 2), (^ 2)]   -- [4,6,9]

Function composition

The dot operator joins two functions into one:

HASKELL
(.) :: (b -> c) -> (a -> b) -> a -> c
(f . g) x = f (g x)

Read f . g as "f after g". The right function runs first. Types must line up: the output type of g is the input type of f.

HASKELL
countLongWords :: String -> Int
countLongWords = length . filter ((> 4) . length) . words

This reads from right to left: split into words, keep those longer than four characters, count them. Notice the inner (> 4) . length composes a section with length, producing a predicate on strings.

Composition reads right to left

words Split the text into words.
filter Keep the long words.
length Count what is left.

length . filter p . words runs words first, length last.

1 / 2

Dot with dollar

A very common pattern ends a composition chain with $ to supply the data:

HASKELL
sumOfOddSquares n = sum . map (^ 2) . filter odd $ [1 .. n]

You cannot write sum . map (^ 2) . filter odd [1 .. n] because application binds tighter than .: it would try to compose with filter odd [1 .. n], a list, not a function, and GHC reports a type error. The $ fixes the grouping.

JS Composition and $ in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line shows a law: composition is associative, and id is its identity (f . id = f = id . f). That is why long chains need no inner parentheses.

flip

flip swaps the first two arguments of a function:

HASKELL
flip :: (a -> b -> c) -> b -> a -> c

flip (-) 1 10          -- 10 - 1 = 9
map (flip div 2) [10, 20]   -- same as (`div` 2): [5,10]

It is useful when a function has its arguments in the wrong order for partial application. Related helpers are const (ignores its second argument), id (returns its argument) and on from Data.Function:

HASKELL
import Data.Function (on)
import Data.List (sortBy, groupBy)

sortBy (compare `on` snd) [(1, 'c'), (2, 'a'), (3, 'b')]
-- [(2,'a'),(3,'b'),(1,'c')]

Writing readable pipelines

Composition is powerful, so use judgement:

  • Aim for chains of three to five clear steps. Give long ones intermediate names with where.
  • Prefer a named helper to a long lambda. isLong = (> 4) . length documents intent.
  • Write a type signature for every top-level pipeline. It acts as documentation and keeps the monomorphism restriction away.
  • Do not go point-free when it hides the data flow. Sometimes f x = foo (bar x) (baz x) is clearer than any dot gymnastics.
JS A readable pipeline

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Haskell's dot runs right to left, while pipe here runs left to right. In Haskell, Data.Function offers (&) for left-to-right application: xs & filter odd & map (* 2).

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does (f . g) x equal?

    Composition applies the right-hand function first: (f . g) x = f (g x).
  2. 2. Why is sum . map (^ 2) . filter odd [1 .. 5] a type error?

    You would need $ before the list: sum . map (^ 2) . filter odd $ [1 .. 5].
  3. 3. What does map ($ 3) [(+ 1), (* 2)] return?

    ($ 3) applies each function to 3: 3 + 1 = 4 and 3 * 2 = 6.
  4. 4. What is flip (-) 1 10?

    flip swaps the arguments, so it computes 10 - 1 = 9.

Summary

  • A lambda \x y -> body is an anonymous function; named definitions are sugar for lambdas.
  • f $ x is application with the lowest precedence; it removes parentheses and is not a loop or special syntax.
  • f . g builds a new function that runs g first; composition is associative with id as identity.
  • sum . map f . filter p $ xs is the usual way to feed data into a composed chain.
  • flip swaps two arguments; keep pipelines short, typed and readable.

Next: Algebraic Data Types.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.