# Difference between revisions of "Partial application"

BrettGiles (talk | contribs) m (→Slightly more complicated: Capitalization) |
m (fix typo) |
||

Line 12: | Line 12: | ||

</haskell> | </haskell> | ||

− | In this example, <hask>addOne</hask> is the result of partially applying <hask>add</hask>. It is a new function that takes | + | In this example, <hask>addOne</hask> is the result of partially applying <hask>add</hask>. It is a new function that takes an integer, adds 1 to it and returns that as the result. |

The important property here is that the <hask>-></hask> operator is right associative, and function application is left associative, meaning the type signature of add actually looks like this: | The important property here is that the <hask>-></hask> operator is right associative, and function application is left associative, meaning the type signature of add actually looks like this: |

## Revision as of 22:22, 24 July 2007

Partial application in Haskell involves passing less than the full number of arguments to a function that takes multiple arguments.

## Examples

### Simple introduction

For example:

```
add :: Int -> Int -> Int
add x y = x + y
addOne = add 1
```

In this example, `addOne`

is the result of partially applying `add`

. It is a new function that takes an integer, adds 1 to it and returns that as the result.

The important property here is that the `->`

operator is right associative, and function application is left associative, meaning the type signature of add actually looks like this:

```
add :: Int -> (Int -> Int)
```

This means that add actually takes one argument and returns a function that takes another argument and returns an Int.

### Slightly more complicated

What if you have a higher order function?

For example:

```
comp2 :: (a -> b) -> (b -> b -> c) -> (a -> a -> c)
comp2 f g = (\x y -> g (f x) (f y))
```

Remembering the maxim that: *Functions are not partial, you can partially apply a function.*

So, is this a partial definition of `comp2'`

?

```
comp2' f = (\x y -> add (f x) (f y))
```

Not really, this is the definition of another function. But you can achieve the desired result by partially applying `comp2`

, like so:

```
comp2' f = comp2 f add
```