Skip to content

Rewrite Currying tour as Multiple Parameter Lists #986

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

Merged
merged 12 commits into from
Jan 22, 2018
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion _ba/tour/case-classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ partof: scala-tour

num: 11
next-page: pattern-matching
previous-page: currying
previous-page: multiple-parameter-lists
prerequisite-knowledge: classes, basics, mutability

---
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion _ba/tour/nested-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ discourse: true
partof: scala-tour

num: 9
next-page: currying
next-page: multiple-parameter-lists
previous-page: higher-order-functions

---
Expand Down
2 changes: 1 addition & 1 deletion _ba/tour/tour-of-scala.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ kao čistom zamjenom za višestruko nasljeđivanje.
Scala je također funkcionalni jezik u smislu da je [svaka funkcija vrijednost](unified-types.html).
Scala ima lahku sintaksu za definisanje anonimnih funkcija,
i podržava [funkcije višeg reda](higher-order-functions.html), omogućuje [ugnježdavanje funkcija](nested-functions.html),
i podržava [curry-jevanje](currying.html).
i podržava [curry-jevanje](multiple-parameter-lists.html).
Scaline [case klase](case-classes.html) i njen mehanizam [podudaranja uzoraka](pattern-matching.html) modeluju algebarske tipove
koji se koriste u dosta funkcionalnih programskih jezika.
[Singlton objekti](singleton-objects.html) omogućuju pogodan način za grupisanje funkcija koje nisu članovi klase.
Expand Down
2 changes: 1 addition & 1 deletion _es/tour/automatic-closures.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ num: 16
language: es

next-page: operators
previous-page: currying
previous-page: multiple-parameter-lists
---

Scala permite pasar funciones sin parámetros como parámetros de un método. Cuando un método así es invocado, los parámetros reales de la función enviada sin parámetros no son evaluados y una función "nularia" (de aridad cero, 0-aria, o sin parámetros) es pasada en su lugar. Esta función encapsula el comportamiento del parámetro correspondiente (comunmente conocido como "llamada por nombre").
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion _es/tour/nested-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ partof: scala-tour
num: 13
language: es

next-page: currying
next-page: multiple-parameter-lists
previous-page: singleton-objects
---

Expand Down
2 changes: 1 addition & 1 deletion _es/tour/tour-of-scala.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Scala es un lenguaje de programación moderno multi-paradigma diseñado para exp
Scala es un lenguaje puramente orientado a objetos en el sentido de que todo es un objeto. Los tipos y comportamientos de objetos son descritos por [clases](classes.html) y [traits](traits.html) (que podría ser traducido como un "rasgo"). Las clases pueden ser extendidas a través de subclases y un mecanismo flexible [de composición mezclada](mixin-class-composition.html) que provee un claro remplazo a la herencia múltiple.

## Scala es funcional ##
Scala es también un lenguaje funcional en el sentido que toda función es un valor. Scala provee una sintaxis ligera para definir funciones anónimas. Soporta [funciones de primer orden](higher-order-functions.html), permite que las funciones sean [anidadas](nested-functions.html), y soporta [currying](currying.html). Las [clases caso](case-classes.html) de Scala y las construcciones incorporadas al lenguaje para [reconocimiento de patrones](pattern-matching.html) modelan tipos algebráicos usados en muchos lenguajes de programación funcionales.
Scala es también un lenguaje funcional en el sentido que toda función es un valor. Scala provee una sintaxis ligera para definir funciones anónimas. Soporta [funciones de primer orden](higher-order-functions.html), permite que las funciones sean [anidadas](nested-functions.html), y soporta [currying](multiple-parameter-lists.html). Las [clases caso](case-classes.html) de Scala y las construcciones incorporadas al lenguaje para [reconocimiento de patrones](pattern-matching.html) modelan tipos algebráicos usados en muchos lenguajes de programación funcionales.

Además, la noción de reconocimiento de patrones de Scala se puede extender naturalmente al procesamiento de datos XML con la ayuda de [patrones de expresiones regulares](regular-expression-patterns.html). En este contexto, seq comprehensions resultan útiles para formular consultas. Estas características hacen a Scala ideal para desarrollar aplicaciones como Web Services.

Expand Down
2 changes: 1 addition & 1 deletion _ko/tour/case-classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ num: 10
language: ko

next-page: pattern-matching
previous-page: currying
previous-page: multiple-parameter-lists
---

스칼라는 _케이스 클래스_ 개념을 지원한다. 케이스 클래스는 아래와 같은 특징을 가지는 일반 클래스이다.
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion _ko/tour/nested-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ partof: scala-tour
num: 8
language: ko

next-page: currying
next-page: multiple-parameter-lists
previous-page: higher-order-functions
---

Expand Down
2 changes: 1 addition & 1 deletion _ko/tour/tour-of-scala.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ next-page: unified-types
[모든 값이 객체](unified-types.html)라는 측면에서 스칼라는 순수 객체지향 언어다. 객체의 타입과 행위는 [클래스](classes.html)와 [트레잇](traits.html)으로 나타난다. 클래스는 서브클래스를 만들거나, 다중 상속을 깔끔하게 대체하는 유연한 [믹스인 기반 컴포지션](mixin-class-composition.html) 방법을 통해 확장된다.

## 스칼라는 함수형이다 ##
또한, 스칼라는 [모든 함수가 값](unified-types.html)이라는 측면에서 함수형 언어다. 스칼라는 익명 함수를 위한 경량 구문을 제공하고, [고차 함수](higher-order-functions.html)를 지원하며, 함수의 [중첩](nested-functions.html)을 허용하고, [커링](currying.html)을 지원한다. 스칼라의 [케이스 클래스](case-classes.html)와 케이스 클래스의 [패턴 매칭](pattern-matching.html) 빌트인 지원을 통해 여러 함수형 프로그래밍 언어에서 사용되는 대수 타입을 만들 수 있다.
또한, 스칼라는 [모든 함수가 값](unified-types.html)이라는 측면에서 함수형 언어다. 스칼라는 익명 함수를 위한 경량 구문을 제공하고, [고차 함수](higher-order-functions.html)를 지원하며, 함수의 [중첩](nested-functions.html)을 허용하고, [커링](multiple-parameter-lists.html)을 지원한다. 스칼라의 [케이스 클래스](case-classes.html)와 케이스 클래스의 [패턴 매칭](pattern-matching.html) 빌트인 지원을 통해 여러 함수형 프로그래밍 언어에서 사용되는 대수 타입을 만들 수 있다.

뿐만 아니라 스칼라의 패턴 매칭 개념은 [우측 무시 시퀀스 패턴](regular-expression-patterns.html)의 도움을 받아 자연스럽게 XML 데이터의 처리로 확장된다. 이런 맥락에서 시퀀스 컴프리헨션은 쿼리를 만들 때 유용하다. 이런 기능 때문에 스칼라는 웹 서비스와 같은 애플리케이션 개발에 있어서 이상적인 선택이 될 수 있다.

Expand Down
2 changes: 1 addition & 1 deletion _pl/tour/case-classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ partof: scala-tour
num: 10
language: pl
next-page: pattern-matching
previous-page: currying
previous-page: multiple-parameter-lists
---

Scala wspiera mechanizm _klas przypadków_. Klasy przypadków są zwykłymi klasami z dodatkowymi założeniami:
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion _pl/tour/nested-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ partof: scala-tour

num: 8
language: pl
next-page: currying
next-page: multiple-parameter-lists
previous-page: higher-order-functions
---

Expand Down
2 changes: 1 addition & 1 deletion _pl/tour/tour-of-scala.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Scala jest nowoczesnym, wieloparadygmatowym językiem programowania zaprojektowa
Scala jest czysto obiektowym językiem w tym sensie, że każda [wartość jest obiektem](unified-types.html). Typy oraz zachowania obiektów są opisane przez [klasy](classes.html) oraz [cechy](traits.html). Klasy są rozszerzane przez podtypowanie i elastyczny mechanizm [kompozycji domieszek](mixin-class-composition.html) jako zastępnik dla wielodziedziczenia.

## Scala jest funkcyjna ##
Scala jest też funkcyjnym językiem w tym sensie, że [każda funkcja jest wartością](unified-types.html). Scala dostarcza lekką składnię do definiowana funkcji anonimowych, wspiera [funkcje wyższego rzędu](higher-order-functions.html), pozwala funkcjom, by były [zagnieżdżone](nested-functions.html), a także umożliwia [rozwijanie funkcji](currying.html). [Klasy przypadków](case-classes.html) oraz wbudowane wsparcie dla [dopasowania wzorców](pattern-matching.html) wprowadzają do Scali mechanizm typów algebraicznych stosowany w wielu funkcyjnych językach programowania. [Obiekty singleton](singleton-objects.html) są wygodną metodą grupowania funkcji, które nie należą do żadnej klasy.
Scala jest też funkcyjnym językiem w tym sensie, że [każda funkcja jest wartością](unified-types.html). Scala dostarcza lekką składnię do definiowana funkcji anonimowych, wspiera [funkcje wyższego rzędu](higher-order-functions.html), pozwala funkcjom, by były [zagnieżdżone](nested-functions.html), a także umożliwia [rozwijanie funkcji](multiple-parameter-lists.html). [Klasy przypadków](case-classes.html) oraz wbudowane wsparcie dla [dopasowania wzorców](pattern-matching.html) wprowadzają do Scali mechanizm typów algebraicznych stosowany w wielu funkcyjnych językach programowania. [Obiekty singleton](singleton-objects.html) są wygodną metodą grupowania funkcji, które nie należą do żadnej klasy.

Ponadto mechanizm dopasowania wzorca w naturalny sposób rozszerza się do obsługi przetwarzania danych w formacie XML z pomocą [wzorców sekwencji ignorujących prawą stronę](regular-expression-patterns.html), z wykorzystaniem rozszerzeń [obiektów ekstraktorów](extractor-objects.html). W tym kontekście instrukcje for są użyteczne w formułowaniu zapytań. Ta funkcjonalność sprawia, że Scala jest idealnym językiem do tworzenia aplikacji takich jak usługi sieciowe.

Expand Down
2 changes: 1 addition & 1 deletion _pt-br/tour/case-classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ partof: scala-tour

num: 10
next-page: pattern-matching
previous-page: currying
previous-page: multiple-parameter-lists
language: pt-br
---

Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion _pt-br/tour/nested-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ discourse: false
partof: scala-tour

num: 8
next-page: currying
next-page: multiple-parameter-lists
previous-page: higher-order-functions
language: pt-br
---
Expand Down
2 changes: 1 addition & 1 deletion _pt-br/tour/tour-of-scala.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Scala é uma linguagem de programação moderna e multi-paradigma desenvolvida p
Scala é uma linguagem puramente orientada a objetos no sentido que [todo valor é um objeto](unified-types.html). Tipos e comportamentos de objetos são descritos por [classes](classes.html) e [traits](traits.html). Classes são estendidas por subclasses e por um flexível mecanismo [de composição mesclada](mixin-class-composition.html) como uma alternativa para herança múltipla.

## Scala é funcional ##
Scala é também uma linguagem funcional no sentido que [toda função é um valor](unified-types.html). Scala fornece uma sintaxe leve para definir funções anônimas, suporta [funções de primeira ordem](higher-order-functions.html), permite funções [aninhadas](nested-functions.html), e suporta [currying](currying.html). As [case classes](case-classes.html) da linguagem Scala e o suporte embutido para [correspondência de padrões](pattern-matching.html) modelam tipos algébricos utilizados em muitas linguagens de programação funcional. [Objetos Singleton](singleton-objects.html) fornecem uma alternativa conveniente para agrupar funções que não são membros de uma classe.
Scala é também uma linguagem funcional no sentido que [toda função é um valor](unified-types.html). Scala fornece uma sintaxe leve para definir funções anônimas, suporta [funções de primeira ordem](higher-order-functions.html), permite funções [aninhadas](nested-functions.html), e suporta [currying](multiple-parameter-lists.html). As [case classes](case-classes.html) da linguagem Scala e o suporte embutido para [correspondência de padrões](pattern-matching.html) modelam tipos algébricos utilizados em muitas linguagens de programação funcional. [Objetos Singleton](singleton-objects.html) fornecem uma alternativa conveniente para agrupar funções que não são membros de uma classe.

Além disso, a noção de correspondência de padrões em Scala se estende naturalmente ao processamento de dados de um XML com a ajuda de [expressões regulares](regular-expression-patterns.html), por meio de uma extensão via [objetos extratores](extractor-objects.html). Nesse contexto, compreensões de sequência são úteis para formular consultas. Essas funcionalidades tornam Scala ideal para desenvolver aplicações como serviços web.

Expand Down
2 changes: 1 addition & 1 deletion _tour/case-classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ partof: scala-tour

num: 11
next-page: pattern-matching
previous-page: currying
previous-page: multiple-parameter-lists
prerequisite-knowledge: classes, basics, mutability

redirect_from: "/tutorials/tour/case-classes.html"
Expand Down
43 changes: 0 additions & 43 deletions _tour/currying.md

This file was deleted.

67 changes: 67 additions & 0 deletions _tour/multiple-parameter-lists.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
layout: tour
title: Multiple Parameter Lists (Currying)

discourse: true

partof: scala-tour

num: 10
next-page: case-classes
previous-page: nested-functions

redirect_from: "/tutorials/tour/multiple-parameter-lists.html"
---

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. This is formally known as [currying](https://en.wikipedia.org/wiki/Currying).

Here is an example, defined in [Traversable](/overviews/collections/trait-traversable.html) trait from Scala collections:

```
def foldLeft[B](z: B)(op: (B, A) => B): B
```

`foldLeft` applies a binary operator `op` to an initial value `z` and all elements of this traversable, going left to right. Shown below is an example of its usage.

Starting with an initial value of 0, `foldLeft` here applies the function `(m, n) => m + n` to each element in the List and the previous accumulated value.

```tut
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val res = numbers.foldLeft(0)((m, n) => m + n)
print(res) // 55
```

Multiple parameter lists have a more verbose invocation syntax; and hence should be used sparingly. Suggested use cases include:

#### Single functional parameter
In case of a single functional parameter, like `op` in the case of `foldLeft` above, multiple parameter lists allow a concise syntax to pass an anonymous function to the method. Without multiple parameter lists, the code would look like this:

```
numbers.foldLeft(0, {(m: Int, n: Int) => m + n})
```

Note that the use of multiple parameter lists here also allows us to take advantage of Scala type inference to make the code more concise as shown below; which would not be possible in a non-curried definition.

```
numbers.foldLeft(0)(_ + _)
```

Also, it allows us to fix the parameter `z` and pass around a partial function and reuse it as shown below:
```tut
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val numberFunc = numbers.foldLeft(List[Int]())_

val squares = numberFunc((xs, x) => xs:+ x*x)
print(squares.toString()) // List(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)

val cubes = numberFunc((xs, x) => xs:+ x*x*x)
print(cubes.toString()) // List(1, 8, 27, 64, 125, 216, 343, 512, 729, 1000)
```

#### Implicit parameters
To specify certain parameters in a parameter list as `implicit`, multiple parameter lists should be used. An example of this is:

```
def execute(arg: Int)(implicit ec: ExecutionContext) = ???
```

2 changes: 1 addition & 1 deletion _tour/nested-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ discourse: true
partof: scala-tour

num: 9
next-page: currying
next-page: multiple-parameter-lists
previous-page: higher-order-functions

redirect_from: "/tutorials/tour/nested-functions.html"
Expand Down
2 changes: 1 addition & 1 deletion _tour/tour-of-scala.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Scala is a modern multi-paradigm programming language designed to express common
Scala is a pure object-oriented language in the sense that [every value is an object](unified-types.html). Types and behavior of objects are described by [classes](classes.html) and [traits](traits.html). Classes are extended by subclassing and a flexible [mixin-based composition](mixin-class-composition.html) mechanism as a clean replacement for multiple inheritance.

## Scala is functional ##
Scala is also a functional language in the sense that [every function is a value](unified-types.html). Scala provides a [lightweight syntax](basics.html#functions) for defining anonymous functions, it supports [higher-order functions](higher-order-functions.html), it allows functions to be [nested](nested-functions.html), and supports [currying](currying.html). Scala's [case classes](case-classes.html) and its built-in support for [pattern matching](pattern-matching.html) model algebraic types used in many functional programming languages. [Singleton objects](singleton-objects.html) provide a convenient way to group functions that aren't members of a class.
Scala is also a functional language in the sense that [every function is a value](unified-types.html). Scala provides a [lightweight syntax](basics.html#functions) for defining anonymous functions, it supports [higher-order functions](higher-order-functions.html), it allows functions to be [nested](nested-functions.html), and supports [currying](multiple-parameter-lists.html). Scala's [case classes](case-classes.html) and its built-in support for [pattern matching](pattern-matching.html) model algebraic types used in many functional programming languages. [Singleton objects](singleton-objects.html) provide a convenient way to group functions that aren't members of a class.

Furthermore, Scala's notion of pattern matching naturally extends to the [processing of XML data](https://github.com/scala/scala-xml/wiki/XML-Processing) with the help of [right-ignoring sequence patterns](regular-expression-patterns.html), by way of general extension via [extractor objects](extractor-objects.html). In this context, [for comprehensions](for-comprehensions.html) are useful for formulating queries. These features make Scala ideal for developing applications like web services.

Expand Down