Translate

lunes, 9 de enero de 2017

Un resumen de Scala for the Impatient, parte 6


Funciones. 

Scala tiene funciones además de métodos. La diferencia es que las funciones no pertenecen a ningún objeto.
Para definir una función solo es necesario, nombre, parámetros y el cuerpo de la función:

def abs(x: Double) = if (x >= 0) x else -x

No es necesario definir el tipo, dado que el compilador lo infiere. En el caso que no pueda inferirlo como funciones recursivas, se le debe indicar.

Si la función debe hacer varias cosas se puede utilizar las llaves:

def fac(n : Int) = {
    var r = 1
    for (i <- 1 to n) r = r * i
     r
}

La función retorna lo ultimo que se ejecuta y no es necesario la palabra return.

Se pueden utilizar valores por defecto para las funciones:

def decorate(str: String, left: String = "[", right: String = "]") =
         left + str + right

Si llamamos a decorate("Hello") , el resultado va a ser :  "[Hello]"
Si llamamos a decorate("Hello", ">>>[") el resultado va a ser : ">>>[Hello]", pero, ¿como podemos llamar a la función con un parámetro para rigth y el default para left? con los parámetros nombrados:

decorate("Hello", right = "]<<<") // Calls decorate("Hello", "[", "]<<<")

Podemos nombrar todos los parámetros:

decorate(left = "<<<", str = "Hello", right = ">>>")

El resultado es "<<<Hello>>>" . Note que el orden de los parámetros no eran iguales que como fueron definidos.

Algunas veces es necesario implementar funciones con un numero variable de parametros, esto se hace con el * :

def sum(args: Int*) = {
    var result = 0
    for (arg <- args) result += arg
    result
}

Y esto se puede llamar de la siguiente manera:

val s = sum(1, 4, 9, 16, 25)
La función recibe un parámetro de tipo Seq pero no podemos pasar una sequencia desde una función por ejemplo esto retornara error:

val s = sum(1 to 5) // Error

Si la función es llamada con un solo argumento este debe ser entero y no rango de enteros, para solucionar este problema se debe agregar _* :

val s = sum(1 to 5: _*) // Consider 1 to 5 as an argument sequence

Si necesitamos llamar a una función recursiva podemos utilizar el mismo artilugio:

def sum(args: Int*) : Int = {
   if (args.length == 0) 0
   else args.head + recursiveSum(args.tail : _*)
}

jueves, 5 de enero de 2017

Top 10 del contenido de InfoQ en el 2016

Me llego un mail muy interesante de infocola o InfoQ, sobre los temas más leídos en el 2016.

Como yo, seguro que se te paso alguno. Por lo que comparto con vos este mail:

January 2017

Top 10 Content of 2016

In this special newsletter we show case the Top 10 content items published on InfoQ in 2016.

Top MiniBooks

The JHipster Mini-book is a guide to getting started with hip technologies today: AngularJS, Bootstrap and Spring Boot. This book shows you how to build an app with JHipster.
What is machine learning? Who is using it? How does it work? What are some real-world uses? Get answers to these questions and so much more in this free eBook! It's like a crash course in machine learning geared specifically for today's modern fraud fighter. Download Now.
SPONSORED CONTENT

Top News

While some applications will have an easy migration path to .NET Core, especially ones based on ASP.NET MVC, others may run into problems. Not just obvious ones such as porting from WinForms or WPF to Universal Windows Applications (UWP), but subtler issues that are deep within the core of the .NET Framework.
Services requiring an enterprise platform built of 100s of shared libraries to be able to run and only allowing approved network clients for talking to services are two anti-patterns, Ben Christensen explained at the recent Microservices Practitioner Summit sharing his experiences from building distributed systems and the trend he sees in increased coupling with binary dependencies.
Over the last year we've shown you various features that were being considered for C# 7. With the preview of Visual Studio 15, Microsoft has decided to demonstrate the features to make it into the final release of C# 7.
You've heard about DevOps and digital transformation. What do they have to do with you, the CIO? How can you make sure your organization is not just current, but staying truly competitive? Download this white paper to get answers to these and other questions. Download Now.
SPONSORED CONTENT

Top Articles

Jean-Jacques Dubray introduces a new pattern, State-Action-Model, that speeds up the development of modern applications and simplifies the interaction between the data model and the view.
Angular 2 & TypeScript have brought true object oriented development to the world's most popular web development framework. This article provides a high-level overview of Angular 2.
In this article, third installment of Apache Spark series, author discusses Apache Spark Streaming framework for processing real-time streaming data using a log analytics sample application.
Modern JavaScript development is in constant motion. In this article, Bonnie Eisenman shows JavaScript newcomers the lay of the land and where to begin.

Top Presentations

Philip Wadler on why category theory is relevant for developers, discussing the principle of Propositions as Types connecting propositions and proofs in logic, and types and programs in computing.
Cliff Click takes a look at Java vs C performance. He discusses both languages' strong and weak points and the programming context surrounding language choices.

Connect with InfoQ on Twitter
Connect with InfoQ on Facebook
Connect with InfoQ on LinkedIn
Connect with InfoQ on Google Plus
Connect with InfoQ on Youtube