Skip to content

Commit

Permalink
add bit about function application with $
Browse files Browse the repository at this point in the history
  • Loading branch information
GoNZooo committed Aug 11, 2021
1 parent c768e55 commit 7bb8c8a
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions basics/01-values-and-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
- [`case` expressions](#case-expressions)
- [Exercises (Asking questions about values)](#exercises-asking-questions-about-values)
- [Exercise notes (Asking questions about values)](#exercise-notes-asking-questions-about-values)
- [Interlude: Function application with `$`](#interlude-function-application-with-)
- [Partial application](#partial-application)
- [Exercises (Partial application)](#exercises-partial-application)
- [Exercise notes (Partial application)](#exercise-notes-partial-application)
Expand Down Expand Up @@ -483,6 +484,35 @@ action of type `IO ()` in each branch when we executed `putStrLn ...`.

0. You don't need `if` for this one.

## Interlude: Function application with `$`

Sometimes you'll want to apply a function and you'll need to parenthesize the expression in order
to do it:

```haskell
safeDivide :: Int -> Int -> DivisionResult
safeDivide _x 0 = DivisionByZero
safeDivide x divisor =
let xAsFloat = fromIntegral x
divisorAsFloat = fromIntegral divisor
-- We want to apply the `DivideSuccess` constructor here to the result of the
-- division, not just `xAsFloat`, so we parenthesize the calculation.
in DivideSuccess (xAsFloat / divisorAsFloat)
```

The above can be written using the `$` operator, which applies the function on the left to the
expression on the right:

```haskell
safeDivide :: Int -> Int -> DivisionResult
safeDivide _x 0 = DivisionByZero
safeDivide x divisor =
let xAsFloat = fromIntegral x
divisorAsFloat = fromIntegral divisor
-- With `$` we no longer need to parenthesize the expression.
in DivideSuccess $ xAsFloat / divisorAsFloat
```

## Partial application

When you apply a function, you can choose to **not** pass all the arguments it's expecting. This
Expand Down

0 comments on commit 7bb8c8a

Please sign in to comment.