diff --git a/_ba/tour/case-classes.md b/_ba/tour/case-classes.md index 84fdc68c98..2f0babb99f 100644 --- a/_ba/tour/case-classes.md +++ b/_ba/tour/case-classes.md @@ -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 --- diff --git a/_ba/tour/currying.md b/_ba/tour/multiple-parameter-lists.md similarity index 100% rename from _ba/tour/currying.md rename to _ba/tour/multiple-parameter-lists.md diff --git a/_ba/tour/nested-functions.md b/_ba/tour/nested-functions.md index 58bb5765e2..f7122a33f8 100644 --- a/_ba/tour/nested-functions.md +++ b/_ba/tour/nested-functions.md @@ -8,7 +8,7 @@ discourse: true partof: scala-tour num: 9 -next-page: currying +next-page: multiple-parameter-lists previous-page: higher-order-functions --- diff --git a/_ba/tour/tour-of-scala.md b/_ba/tour/tour-of-scala.md index fd506be132..326c8bade4 100644 --- a/_ba/tour/tour-of-scala.md +++ b/_ba/tour/tour-of-scala.md @@ -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. diff --git a/_es/tour/automatic-closures.md b/_es/tour/automatic-closures.md index a04500bca2..a6eba7b6c5 100644 --- a/_es/tour/automatic-closures.md +++ b/_es/tour/automatic-closures.md @@ -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"). diff --git a/_es/tour/currying.md b/_es/tour/multiple-parameter-lists.md similarity index 100% rename from _es/tour/currying.md rename to _es/tour/multiple-parameter-lists.md diff --git a/_es/tour/nested-functions.md b/_es/tour/nested-functions.md index 01f706872d..3813a2b905 100644 --- a/_es/tour/nested-functions.md +++ b/_es/tour/nested-functions.md @@ -9,7 +9,7 @@ partof: scala-tour num: 13 language: es -next-page: currying +next-page: multiple-parameter-lists previous-page: singleton-objects --- diff --git a/_es/tour/tour-of-scala.md b/_es/tour/tour-of-scala.md index 5c3caa3956..e6c48a537d 100644 --- a/_es/tour/tour-of-scala.md +++ b/_es/tour/tour-of-scala.md @@ -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. diff --git a/_ko/tour/case-classes.md b/_ko/tour/case-classes.md index a68a61d7a0..6d32c6bac2 100644 --- a/_ko/tour/case-classes.md +++ b/_ko/tour/case-classes.md @@ -10,7 +10,7 @@ num: 10 language: ko next-page: pattern-matching -previous-page: currying +previous-page: multiple-parameter-lists --- 스칼라는 _케이스 클래스_ 개념을 지원한다. 케이스 클래스는 아래와 같은 특징을 가지는 일반 클래스이다. diff --git a/_ko/tour/currying.md b/_ko/tour/multiple-parameter-lists.md similarity index 100% rename from _ko/tour/currying.md rename to _ko/tour/multiple-parameter-lists.md diff --git a/_ko/tour/nested-functions.md b/_ko/tour/nested-functions.md index d7eed785cf..9f55347977 100644 --- a/_ko/tour/nested-functions.md +++ b/_ko/tour/nested-functions.md @@ -9,7 +9,7 @@ partof: scala-tour num: 8 language: ko -next-page: currying +next-page: multiple-parameter-lists previous-page: higher-order-functions --- diff --git a/_ko/tour/tour-of-scala.md b/_ko/tour/tour-of-scala.md index 66dbd5e0e0..62b150e50a 100644 --- a/_ko/tour/tour-of-scala.md +++ b/_ko/tour/tour-of-scala.md @@ -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 데이터의 처리로 확장된다. 이런 맥락에서 시퀀스 컴프리헨션은 쿼리를 만들 때 유용하다. 이런 기능 때문에 스칼라는 웹 서비스와 같은 애플리케이션 개발에 있어서 이상적인 선택이 될 수 있다. diff --git a/_pl/tour/case-classes.md b/_pl/tour/case-classes.md index 831277f07b..f218595b71 100644 --- a/_pl/tour/case-classes.md +++ b/_pl/tour/case-classes.md @@ -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: diff --git a/_pl/tour/currying.md b/_pl/tour/multiple-parameter-lists.md similarity index 100% rename from _pl/tour/currying.md rename to _pl/tour/multiple-parameter-lists.md diff --git a/_pl/tour/nested-functions.md b/_pl/tour/nested-functions.md index 0f905aff11..1839a2da62 100644 --- a/_pl/tour/nested-functions.md +++ b/_pl/tour/nested-functions.md @@ -8,7 +8,7 @@ partof: scala-tour num: 8 language: pl -next-page: currying +next-page: multiple-parameter-lists previous-page: higher-order-functions --- diff --git a/_pl/tour/tour-of-scala.md b/_pl/tour/tour-of-scala.md index 0f3f1d255f..896f6a1702 100644 --- a/_pl/tour/tour-of-scala.md +++ b/_pl/tour/tour-of-scala.md @@ -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. diff --git a/_pt-br/tour/case-classes.md b/_pt-br/tour/case-classes.md index e2eb9fa655..238197cf70 100644 --- a/_pt-br/tour/case-classes.md +++ b/_pt-br/tour/case-classes.md @@ -8,7 +8,7 @@ partof: scala-tour num: 10 next-page: pattern-matching -previous-page: currying +previous-page: multiple-parameter-lists language: pt-br --- diff --git a/_pt-br/tour/currying.md b/_pt-br/tour/multiple-parameter-lists.md similarity index 100% rename from _pt-br/tour/currying.md rename to _pt-br/tour/multiple-parameter-lists.md diff --git a/_pt-br/tour/nested-functions.md b/_pt-br/tour/nested-functions.md index 6783c3795e..527856d37d 100644 --- a/_pt-br/tour/nested-functions.md +++ b/_pt-br/tour/nested-functions.md @@ -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 --- diff --git a/_pt-br/tour/tour-of-scala.md b/_pt-br/tour/tour-of-scala.md index 01f75ac1a9..bb16f487cf 100644 --- a/_pt-br/tour/tour-of-scala.md +++ b/_pt-br/tour/tour-of-scala.md @@ -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. diff --git a/_tour/case-classes.md b/_tour/case-classes.md index 0768cec5af..607e449d0e 100644 --- a/_tour/case-classes.md +++ b/_tour/case-classes.md @@ -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" diff --git a/_tour/currying.md b/_tour/currying.md deleted file mode 100644 index 3eb04060a4..0000000000 --- a/_tour/currying.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -layout: tour -title: Currying - -discourse: true - -partof: scala-tour - -num: 10 -next-page: case-classes -previous-page: nested-functions - -redirect_from: "/tutorials/tour/currying.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. - -Here is an example: - -```tut -object CurryTest extends App { - - 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 modN(n: Int)(x: Int) = ((x % n) == 0) - - val nums = List(1, 2, 3, 4, 5, 6, 7, 8) - println(filter(nums, modN(2))) - println(filter(nums, modN(3))) -} -``` - -_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`._ - -Here's the output of the program above: - -``` -List(2,4,6,8) -List(3,6) -``` diff --git a/_tour/multiple-parameter-lists.md b/_tour/multiple-parameter-lists.md new file mode 100644 index 0000000000..113ae59f81 --- /dev/null +++ b/_tour/multiple-parameter-lists.md @@ -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) = ??? +``` + \ No newline at end of file diff --git a/_tour/nested-functions.md b/_tour/nested-functions.md index 8cf3e903b5..9ec45648d3 100644 --- a/_tour/nested-functions.md +++ b/_tour/nested-functions.md @@ -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" diff --git a/_tour/tour-of-scala.md b/_tour/tour-of-scala.md index 1cefe23c23..1a4e20a069 100644 --- a/_tour/tour-of-scala.md +++ b/_tour/tour-of-scala.md @@ -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.