Skip to content

Instantly share code, notes, and snippets.

@rodobarcaaa
Created October 10, 2023 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodobarcaaa/ece780f6cddd7ca6586e57d7d0b69ebd to your computer and use it in GitHub Desktop.
Save rodobarcaaa/ece780f6cddd7ca6586e57d7d0b69ebd to your computer and use it in GitHub Desktop.
Scala Functions Examples
object Functions extends App {
//Existen dos formas de declarar las funciones
// Una función básica y conocida acá como callByValue
def sum(x: Int, y: Int) = x + y
// Como la invocamos
sum(1, 2) // 3
// Otra conocida acá como callByName donde pasamos otra función
def product(x: => Int, y: => Int) = x * y
// Como la invocamos
def two() = 2
product(two(), 6) // 12
// U otro un poco más avanzado donde pasamos una función a ejecutar
// Y además notemos que podemos poner parámetros por default
def productF(f: Int => Int, x: Int, y: Int = 2) = f(x * y)
// Como la invocamos
// Definimos una función val
val sum5: Int => Int = x => x + 5 // ó simplemente _ + 5
// Pasamos la misma por parametros
productF(sum5, 6, 6) // (6 * 6) + 5 = 41
// Invocamos sin el ultimo valor para que tome 2 po default
productF(sum5, 5) // (5 * 2) + 5 = 15
// Podemos pasar como en otros lenguajes un array de parámetros
def sumAll(x: Int, y: Int, others: Int*) = {
x + y + others.sum
}
// Como la invocamos
sumAll(1, 2, 3, 4, 5, 6, 7, 8, 9) // 45
// O podemos implementar el método product con un ejemplo de forma recursiva
def productRecursive(numbers: List[Int]): Int = numbers match {
case Nil => 1 // Si la lista es vacía retornamos 1
case x :: tail => x * productRecursive(tail) // Sino multiplicamos
}
productRecursive(List(1, 2, 3, 4, 5)) // 120
//Cerramos con un ejemplo de currying
def sumCurrying(x: Int)(y: Int): Int = x + y
// Como la invocamos
sumCurrying(1)(2) // 3
// Pero podemos entonces almacenar una suma parcial en una variable
val sum2 = sumCurrying(2) _
// y luego invocarla con ese adelanto
sum2(3) // 5
//O que el segundo parámetro se inplicito de un contexto particular
def productCurrying(x: Int)(implicit y: Int): Int = x * y
// Definimos el implicito
implicit val number3: Int = 3
// Ahora consumimos con un solo parámetro y el otro lo encontrará y usará number3
productCurrying(5) // 15
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment