Functional Programming: Solving typical problems with Lists in Scala

Here are some solutions in Scala for typical problems with Lists that may arise when developing larger tasks, these ones can become repetitive over time and they could be used as a “recipe”. Also, they’re classic/basic problems for practice.

  •  Five different ways to create a function that returns a list of N elements:
def a(n: Int): List[Int] = List.fill(n)(1) 
def b(n: Int): List[Int] = (1 to n).toList 
def c(n: Int): List[Int] = if(n == 0) Nil else n :: c(n-1) 
def d(n: Int): List[Int] = List.tabulate(n)(n => 1) 
def e(n: Int): List[Int] = List.range(0,n)

 

  • Create a function that reverses a list without using the native Scala reverse method:
def rev(l: List[Any]): List[Any] = l match {
   case Nil => l
   case head :: tail => rev(tail) ::: List(head)
}

 

  •  Given a list, repeat each element in the list N amount of times:

def f(n: Int, ls: List[Int]): List[Int] = ls.flatMap(List.fill(n)(_))

 

  •  Filter a given list of integers and output only those values that are less than a specified value:

 

def g(delim: Int, ls: List[Int]): List[Int] = for(i <- ls if i < delim) yield i

 

 

  • For a given list with N integers, return a new list removing the elements at odd positions:
def removeOdds(ls: List[Int]): List[Int] = {ls.zipWithIndex.filter(_._2 % 2 != 0).map(_._1)}

 

  • Create a function that returns the sum of the odd elements from a list:
def sumOdds(ls: List[Int]): Int = ls.filter(x => x % 2 != 0).sum

 

  • Create a function that returns the size of a list of integers without using the native Scala length method:
def s(ls: List[Int]): Int = {
    var size = 0
    for(i <- ls) size = size + 1
    size
}
Advertisements

Tech Talent from Venezuela strives for the good of the nation

usb

 

    Despite several complications over the past years of conflicted aura in Venezuela’s sociopolitical context and the evident economic disturbances, a tech-savvy group of young developers, entrepreneurs and enthusiasts has arisen in middle of an almost war conflicted nation, these youngsters are giving their best efforts to contribute for the improvement and the good of the nation. Some of the most talented Computer Science graduates from the country have been setting the bar high with the main purpose of overcome the problems that flooded the nation. Technology can improve our lives and we have a mission, we must use the tools and education to make of our country a better place. These are some of the Venezuelan startups that have been working hard to deliver all their efforts with the goal of making things better.
VENEZUELA (1)

 

  • Akdemia: With their motto Make Schools Awesome they got it right, because not only Venezuela but also the world needs access to better education. Managing a team of young developers, mainly from the Universidad Simón Bolívar in Sartenejas, they have built a beautifully designed software specifically for handling student grades, reports, assignments and real-time notifications for parents.
  • Take a Hand: Originally formed in Venezuela and today also established in Chile, Take a Hand has designed ergonomic and anthropometric adaptations of functional prosthetic systems for fingers, hands and arms. With a line of research of lower limb prosthetics, their main goal is to bring happiness for those in need.
  • Predictvia: Straight out from Caracas, and currently with headquarters in Miami, Florida, Predictvia is truly in its element. Their platform allows clients to predict behavior from current and potential customers. The Blackbox program from Google, explicitly designed for entrepreneurs, has selected them recently for further improvement.
  • ZOI: A great amount of Venezuelan landscapes are unique, and with that in mind, ZOI Venezuela has created a community that targets experiences all across the outstanding landscapes of the country. Scuba Diving, Hiking and Canyoning between other activities, demonstrate that Venezuela’s environment got it all to recover those past times and become again a perfect touristic destination.
  • Learnsity: This interesting Udacity-like platform, wants to connect experts in different topics from all around the world. Photography, HTML, CSS and National Regulations are only a few of the topics handled by several courses in the application where creators can also earn money for their work.
    It’s also remarkable the fact that an interesting number of Venezuelan CS graduates have also been taken into account by big companies like Google, Facebook, Amazon and Microsoft while another important group is working for startups and Software companies from almost all corners of the world. Also, it’s true that Venezuela is going across many difficulties at the moment, but young determined students can overcome any obstacles and is quite common to find them crafting their own ideas from scratch in the web, designing compilers in programming languages like Haskell, Ruby and Python under supervision of dedicated professors or obtaining important results in the ACM-ICPC programming contests.

 

    Although it’s completely true that overcoming the current situation represents a titanic labor, there are interesting examples of countries using technology to push for the improvement of their nations, like IndiaVietnam, and Lithuania among others. It’s also a fact, that management has great responsibility, and to become a better society, we need fundamental changes in the structure and move towards a vast improvement in the overall conditions for everyone involved in the IT industry.

 

    The reality of the country is a constant struggle, but the will to make huge changes comes from powerful ideas. Let’s hope the best of the efforts from our new generations and let’s make use of technology for the good of the nation, that’s definitely a matter of honor, and the country claims for it. It’s quite clear that politicians on turn aren’t interested on the development of the country, but as individuals we must push and use all we have learned to make the change, because we all are the change.

Data Visualization in D3.js for the Venezuelan National Soccer Team

It’s often typical nowadays inside organizations, the extraction of valuable information from big amounts of pooled data inside of their servers. In the past years and even in our days, companies are relying on Excel spreadsheets to analyze the most important bits in a more readable format.

Nonetheless, it’s still hard to understand several lines of text laying inside a table of cells, it’s easier for the human eye, to understand graphic representations of data. Here is where the D3.js magic comes into action.

As its own website defines, D3.js is a JavaScript library for manipulating documents based on data, using HTML, SVG, and CSS.

In this example, I will use statistical data from the Venezuelan National Soccer Team to build a bar chart for the top scorers of all times.

1) First, we define an array of arrays, using the player name as the key and the number of goals as the value. Keep in mind that for this example we are going to use static data, but of course this can be changed in order to make it work dynamically, for example using AJAX to make a data request to our server.

var scorers = [["Juan Arango", 22],
               ["Giancarlo Maldonado", 22],
               ["Salomón Rondón", 14],
               ["Ruberth Morán", 14],
               ["Miku", 11],
               ["José Manuel Rey", 11],
               ["Daniel Arismendi", 9],
               ["Gabriel Urdaneta", 9],
               ["Juan García", 7],
               ["Ricardo David Páez", 7], 
               ["Oswaldo Vizcarrondo", 7]
               ];

2) As a second step, we define the scale. Scales are functions that map from an input domain to an output range, in D3.js we can define it with this line of code:

   var scale = d3.scale.linear().domain( [0 , domain] ).range( [0,600] );

 

Take into account that we have previously defined the domain for the scale:

   var domain = d3.max( scorers , function(d){ return d[1]; });

3)  After this, we select the chart class, and take all the ‘divs’ inside. Then we attach the data to the selected element(s). We also set the width of the ‘div’ using the scale mapping function that we defined previously. Finally, we render the text inside the bar charts (the one that holds the player name and number of goals).

     
        d3.select(".chart")         
	.selectAll("div")
	.data(scorers) 
	.enter().append("div")
	.style("width", function(d) {return scale(d[1]) + "px";}) 
	.html(function(d) { return d[0] + ": " + d[1] + " goals"; });

 

4) Finally, we obtain the bar chart showing the top scorers of the Venezuelan National Team. This way, it’s easier to state that Juan Arango and Giancarlo Maldonado are the maximum scorers of all times with 22 goals playing for the “Vinotinto”, and in a descendent scale, we can watch the rest of the players who have earned a place in the history of Venezuelan soccer.

See the Pen GZEjxZ by Dario Carrasquel (@jeetkunecoder) on CodePen.