miércoles, 10 de abril de 2024

Funciones anónimas en Gleam


 import gleam/io


pub fn main() {

  // Assign an anonymous function to a variable

  let add_one = fn(a) { a + 1 }

  io.debug(twice(1, add_one))


  // Pass an anonymous function as an argument

  io.debug(twice(1, fn(a) { a * 2 }))

}


fn twice(argument: Int, my_function: fn(Int) -> Int) -> Int {

  my_function(my_function(argument))

}


Además de las funciones con nombre a nivel de módulo, Gleam tiene literales de funciones anónimas, escritas con la sintaxis fn() { ... }.

Las funciones anónimas se pueden utilizar indistintamente con funciones con nombre.

No hay comentarios.:

Publicar un comentario