Skip to content

Rewrote currying tour #732

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 16 additions & 17 deletions tutorials/tour/_posts/2017-02-13-currying.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,28 @@ previous-page: nested-functions

Methods may define multiple parameter lists. When a method is called with a fewer number of parameter lists, then this will yield a function taking the missing parameter lists as its arguments.

Here is an example:

```tut
object CurryTest extends App {
import scala.math.pow

def filter(xs: List[Int], p: Int => Boolean): List[Int] =
if (xs.isEmpty) xs
else if (p(xs.head)) xs.head :: filter(xs.tail, p)
else filter(xs.tail, p)
def getTotal(interestRate: Double, years: Int)(principal: Double) = {
principal * pow(1 + interestRate, years)
}
val savingsAccountsPrincipals = Seq(1000.0, 2000.0, 3000.0)
val totals = savingsAccountsPrincipals.map(getTotal(interestRate = .10, years = 20)) // List(6727.499949325611, 13454.999898651222, 20182.499847976833)
```
The method `getTotal` takes two argument lists. The first contains `interestRate` and `years` is the same among all of the savings accounts. The second list contains the `principal` which varies between accounts. When we call `getTotal(interestRate = .10, years = 20)`, this returns getTotal with the second parameter list `(principal: Double)`.

def modN(n: Int)(x: Int) = ((x % n) == 0)
If you're not passing the curried function as an argument, you can use an `_` in place of the second parameter list.

val nums = List(1, 2, 3, 4, 5, 6, 7, 8)
println(filter(nums, modN(2)))
println(filter(nums, modN(3)))
}
```
import scala.math.pow

_Note: method `modN` is partially applied in the two `filter` calls; i.e. only its first argument is actually applied. The term `modN(2)` yields a function of type `Int => Boolean` and is thus a possible candidate for the second argument of function `filter`._
def getTotal(interestRate: Double, years: Int)(principal: Double) = {
principal * pow(1 + interestRate, years)
}

Here's the output of the program above:
val getTotalInTwentyYears = getTotal(interestRate = .10, years = 20)_

val total = getTotalInTwentyYears(2000.0) // 13454.999898651222
```
List(2,4,6,8)
List(3,6)
```
Here `getTotalInTwentyYears` is a function which takes the second parameter list from `getTotal`.