background preloader

Scala

Facebook Twitter

Between Zero & Hero - Scala Tips and Tricks for the intermediate Scala developer. Extreme Cleverness: Functional Data Structures in Scala.

Akka

Scala vs Clojure - Round 2: Concurrency! The time for ignoring concurrency has almost passed. If you read my last post you'll know that I'm looking at Scala Vs Clojure and a big part of both of these languages is their support for concurrency. Scala uses an Erlang inspired actor model, which is a distributed approach to concurrency. Clojure on the other hand leans on it's STM, a non-distributed approach - Lets put them in the ring together! The goal My last post sparked heavy debate in the #scala camp, wherein many frustrations and concerns were expressed by the Scala community. The problem An old concurrency problem/exercise is 'The sleeping barber' and you can either read the full definition here or read my shorter version here: We simulate a barber-shop with 1 barber, 3 waiting chairs and 1 chair for haircutting.The barber sleeps between customers and is thus awoken when one enters the shop.

This is a perfect problem for comparing these two languages for the following reasons Actors scala> Redford ! Software Transactional Memory. An Introduction To Scala Parser Combinators - Part 1: Parser Basics. Lots And Lots Of foldLeft Examples | Matt Malone's Old-Fashioned Software Development Blog. In my last post I reviewed the implementation of scala.List’s foldLeft and foldRight methods. That post included a couple of simple examples, but today I’d like to give you a whole lot more.

The foldLeft method is extremely versatile. It can do thousands of jobs. Of course, it’s not the best tool for EVERY job, but when working on a list problem it’s a good idea to stop and think, “Should I be using foldLeft?” Below, I’ll present a list of problem descriptions and solutions. I thought about listing all the problems first, and then the solutions, so the reader could work on his own solution and then scroll down to compare. Sum Write a function called ‘sum’ which takes a List[Int] and returns the sum of the Ints in the list.

I’ll explain this first example in a bit more depth than the others, just to make sure we all know how foldLeft works. These two definitions above are equivalent. In the first defintion, foldLeft’s second parameter (a function literal) uses explicitly named parameters. Scalacheat. Scala Collections for the Easily Bored Part 2: One at a Time. 28 Jul 2008 As I hinted previously, this series is intended to delve into Scala’s extensive collections API and the many ways in which it can make your life easier. Probably the most important operations you could ever perform on collections are those which examine each element, one at a time. After all, what’s a more common array idiom than looping over all values? In that vein, this article starts by looking at foreach, the imperative programmer’s bread-and-butter when it comes to types like Array and List.

But rather than just stopping there, we also will look at more powerful, higher-order operations like fold, map and the ever-mysterious: flatMap. Iterating As I said above, looping over every item in a collection is probably the most heavily used operation in a programmer’s repertoire. This code should be old hat to anyone coming from a Java background. The same approach is taken in Scala. Here we define an anonymous method (Scala’s name for a closure) which takes a single parameter. Scala in practice: Composing Traits – Lego style. As a kid, i loved to play with Lego bricks, especially to build freaky spacecrafts. At that time it was easy to let my phantasy go (where noone has gone before) and build completely new models simply by composing some standard bricks.

Those bricks weren’t too specialized, meaning that there weren’t too many constraints on how to combine them. On the other side you always had to compose a new spacecraft from the very ground up as there weren’t some more higher organized units like engines or control cabins. Nowadays, you’ll find such units. There are engines, control cabins or a whole commando bridge, Wings, Field Generators and so on – a whole set of higher organized units whithin a single domain. On the other side, you can’t combine every unit with an arbitrary other unit within that domain since there are some ‘constraints’ that will prohibit some unsound combinations.

Now you may ask how that cute childhood story relates to Scala? Look, it’s a spacecraft Captains place Wiring Summary.

Joauth

Steve.vinoski.net/pdf/IC-Scala_Web_Frameworks.pdf. RFC 5849 - The OAuth 1.0 Protocol. [Docs] [txt|pdf] [draft-hammer-oauth] [Diff1] [Diff2] [Errata] Obsoleted by: 6749 INFORMATIONAL Errata Exist Internet Engineering Task Force (IETF) E. Hammer-Lahav, Ed. Request for Comments: 5849 April 2010 Category: Informational ISSN: 2070-1721 Abstract OAuth provides a method for clients to access server resources on behalf of a resource owner (such as a different client or an end- user). It also provides a process for end-users to authorize third- party access to their server resources without sharing their credentials (typically, a username and password pair), using user- agent redirections.

Status of This Memo This document is not an Internet Standards Track specification; it is published for informational purposes. This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. RFC 5849 OAuth 1.0 April 2010 Table of Contents 1. RFC 5849 OAuth 1.0 April 2010 1. 1.1. 1.2. 1.3. Oauth - Revision 1271: /code/java.

Finagle

Damn Cool Algorithms, Part 1: BK-Trees. Posted by Nick Johnson | Filed under coding, tech, damn-cool-algorithms This is the first post in (hopefully) a series of posts on Damn Cool Algorithms - essentially, any algorithm I think is really Damn Cool, particularly if it's simple but non-obvious. BK-Trees, or Burkhard-Keller Trees are a tree-based data structure engineered for quickly finding near-matches to a string, for example, as used by a spelling checker, or when doing a 'fuzzy' search for a term. The aim is to return, for example, "seek" and "peek" if I search for "aeek". What makes BK-Trees so cool is that they take a problem which has no obvious solution besides brute-force search, and present a simple and elegant method for speeding up searches substantially.

BK-Trees were first proposed by Burkhard and Keller in 1973, in their paper "Some approaches to best match file searching". Before we can define BK-Trees, we need to define a couple of preliminaries. The tree is N-ary and irregular (but generally well-balanced). A Tale of 3 Nightclubs. * Part Zero : 10:15 Saturday Night * (In which we will see how to let the type system help you handle failure)... * First let's define a domain. (All the following requires scala 2.9.x and scalaz 6.0) import scalaz. import Scalaz object Sobriety extends Enumeration { val Sober, Tipsy, Drunk, Paralytic, Unconscious = Value } object Gender extends Enumeration { val Male, Female = Value } case class Person(gender : Gender.Value, age : Int, clothes : Set[String], sobriety : Sobriety.Value) * Let's define a trait which will contain the checks that *all* nightclubs make!

Trait Nightclub { //First CHECK def checkAge(p : Person) : Validation[String, Person] = if (p.age < 18) "Too Young! ". else if (p.age > 40) "Too Old! ". else p.success //Second CHECK def checkClothes(p : Person) : Validation[String, Person] = if (p.gender == Gender.Male && ! "Smarten Up! ". else if (p.gender == Gender.Female && p.clothes("Trainers")) "Wear high heels".fail //Third CHECK def checkSobriety(p : Person): Validation[String, Person] for { Monads, Monoids and Scala. Revolute (Lightning Talk @ Big Data Scala meetup) Akka Future vs. Twitter's Finagle Future.

Play framework

Functional Scala: Polymorphic Functions ?!? Welcome to another episode of Functional Scala! If you’re coming from the object oriented world, chances are good that you’ve already heard something about a concept called Polymorphism. You may also know that there are different classes of Polymorphism out there: most of us are familiar with so called (Sub-)Type polymorphism and Parametric polymorphism (you may call it Generics). Since functions take a central role within Functional Programming (i need to mention this, in case you’ve forgotten it), we want to take a closer look if Scala allows for so called polymorphic functions, which plays in the area of parametric polymorphism.

If you’re now asking what the heck do we need polymorphic functions for (if anything), you’re coming to the right place! Parametric polymorphism on types Let’s start the journey and take a look at an example of a polymorphic type, coming from well- known ground: Lists … You may know, that a List can take elements of an arbitrary type. Looks easy! Ouch! Scala Style Guide. Iterating over Map with Scala.

Lift

Scala Days 2012 17-04-12. Video | Scala Days 2011. JCR with Scala « contentGoesHere. Having seen Scala being mentioned in a recent comment I thought I'd give it a try with JCR. First I installed the Scala Plugin for Eclipse. Alternatively I could have also used Scala's command line tools. Then I created a new Scala project from within the Eclipse IDE and put the Jackrabbit jars on the classpath. Now I set out to implement Hop 3 from the article First Hops with Jackrabbit. The main method is a straight forward translation from java. The dump method takes a Node argument and recursively outputs its properties and its child nodes. Using Scala for JCR programming seems very promising. (*) <rant>This is in some ways similar to implicit type conversion in C++ but done right (i.e. more powerful and safer).

Writing modules for Play 2, part 1: Get something working | Objectify. A couple of weeks ago, I migrated the Play! Framework 1.x version of Deadbolt to the Play 2 platform, and was surprised at the lack of information on creating modules. This topic was covered in detail in the Play 1.x docs, and this made creating modules very simple.

Clearly, something needed to be done – and so this is the first in a three-part series on creating modules and plugins for Play 2. It’s important to note this is not a definitive guide – instead, it’s a collection of the information and techniques I’ve used when working on my own modules. I’m going to assume you already have a working installation of Play 2 – if you don’t, head over to for details on how to set this up. In this first part, we’re going to cover the fundamentals of creating and publishing the module, and adding a sample application. First, a small note on the difference between a module and a library. In Play 2, the line is blurred to some degree. 1. 2.

Functional IO in Scala with Scalaz | StackMob. Functional IO in Scala with Scalaz Last time we posted on Scalaz we looked at it from 30-thousand feet, exploring the generic concepts that make up the library’s foundation. This time, we will focus on a core concept which Scalaz gives us the abstraction for: Functional IO! Functional IO is not a concept given to us by Scalaz but instead it comes from the functional programming paradigm. Scalaz gives us an implementation of this. We will be exploring both in this post. When I was first introducing myself to Functional Programming I had a hard time wrapping my head around how one would limit side-effects yet still get stuff done in the real world.

So how do we write functions that perform side-effects yet are still pure? In Scalaz, we represent this idea using the IO[A] trait, in scalaz.effects. IO gives us everything we need to construct our input-output actions, but first, we must know how to take our normal functions that perform input-output and make them into an IO. Comments comments. All that jazz. How do I apply the pimp-my-library pattern to Scala collections. Dependency injection in Scala with Play 2: it’s free | Julien Richard-Foy. When you write a software you generally split it into several modules with no hardcoded dependencies between them so you can reuse and test them more easily: you just need to wire the different modules together at startup according to your desired configuration.

In the Java world, some tools help to perform the wiring task, e.g. Spring or Guice, but in Scala you can perform dependency injection without having to rely on an external tool, as you’ll see in this post where I’ll show how to apply the Cake pattern in the context of a Play 2 application. An example of use case where you may want to use a dependency injection mechanism is when you write a web application which needs the user to be authenticated to perform some actions. During development time it’s generally more comfortable to bypass the authentication step (when you just want to quickly test features you are coding right now).

Well, how can we define an authentication process in Play 2? Now we are almost done! @codemonkeyism Scala Goodness: Tuples. January 11, 2010 by Stephan Schmidt Scala has a wonderful feature: Tuples. As others have already written, tuples are very simple but powerful. Especially if you come from Java, they solve some problems easily, that were ugly in Java. What are tuples? Tuples are containers for values. In Scala you create a Tuple with: scala> val t = (1,2) t: (Int, Int) = (1,2) which is syntactic sugar for scala> val t = new Tuple2(1,2) t: (Int, Int) = (1,2) as Tuples are plain classes in the Scala library. Values in tuples don’t need to be of the same type as shown here scala> val t = (1, "Codemonkeyism") t: (Int, java.lang.String) = (1,Codemonkeyism) which is one reason you should not think of them as collections (see below).

After creating a tuple there are several ways of accessing the values: scala> t res2: (Int, Int) = (1,2) scala> t._1 res3: Int = 1 scala> t._2 res4: Int = 2 Beside accessing the values “by index”, most often it’s more readable to depack tuples into variables. Tuples are not collections. Infinite Lists for the Finitely Patient. 17 Nov 2008 Functional programming has a lot of weird and abstract concepts. Monads of course are the poster child for all that is strange and confusing in functional languages, but there are other examples. At first glance, it seems that the concept of an infinite list would be just as bizarre and incomprehensible as anything else in the paradigm, but really things aren’t as bad as all that.

In fact, even the die-hard imperative programmer can likely benefit from the patterns and techniques enabled by this obtuse construct. For the first part of the article, I’m going to use a lot of examples involving numbers. If you’re already familiar with the semantics of infinite lists, feel free to skip to the section answering that all-important question: Why Do We Care? Syntax Before we dive into the topic of infinite lists and how they are practically applicable, it’s important to understand the underlying mechanics and (critically) how the API works in practice. Requesting n = 0 Surprised? Scala or Java? Exploring myths and facts. The popularization of the Scala programming language, noticeable by the abundance of opinions and criticism on blogs and social networks (like this one by Nikita Ivanov from GridGain and the popular Yammer case), greatly increased the amount of information about the language. However, the quality of such information often leaves much to be desired.

Whether those opinions are favorable or contrary to the Scala, they often contain outdated, superficial or biased statements. The goal of this article is to help those learning or evaluating Scala to come into their own conclusions. It presents the most common questions about language and its environment and, for each one, added clarifications, examples and links, favoring the formation of a better opinion or a more accurate assessment. Scala is a compiled language, designed to run on a managed environment, most likely the JVM, and offers the union of the functional and object-oriented paradigms. Is Scala more productive than Java? In Java: