Maarten ten Velden
Maarten ten Velden

Reputation: 55

How does this usage of the composition operator work without a second argument?

I came across a usage of the . operator that I don't quite understand.

I tried to reason about it myself, but the conclusion I reach is different from what GHCI produces.

I'm using :t to inspect the type of the expression.

The functions I'm using are the last and (.), which have the following signatures:

last :: [a] -> a
(.) :: (b -> c) -> (a -> b) -> a -> c

The function I am confused about is this:

(last .)

I am not sure what this construct is, but I assumed that it would be similar to function composition. Using my reasoning, I would expect this to produce the following function:

(last .) :: (b -> [c]) -> (a -> b) -> a -> [c]

What :t actually gives me is this:

(last .) :: (a -> [c]) -> a -> c

Upvotes: 3

Views: 61

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

This is an example of infix operator sectioning [Haskell-wiki]:

(...)

(2^) (left section) is equivalent to (^) 2, or more verbosely \x -> 2 ^ x.

So we here constructed a function that looks like:

\f -> last . f

or shorter:

(.) last

The (.) :: (b -> c) -> (a -> b) -> a -> c function takes two functions g and h, and creates a function \x -> g (h x). Here g is thus last.

We thus created a function that takes as input a function f :: b -> [c], that then returns last . f.

Upvotes: 6

Related Questions