background preloader

S-99: Ninety-Nine Scala Problems

S-99: Ninety-Nine Scala Problems
These are an adaptation of the Ninety-Nine Prolog Problems written by Werner Hett at the Berne University of Applied Sciences in Berne, Switzerland. I (Phil Gold) have altered them to be more amenable to programming in Scala. Feedback is appreciated, particularly on anything marked TODO. The problems have different levels of difficulty. Those marked with a single asterisk (*) are easy. Your goal should be to find the most elegant solution of the given problems. Solutions are available by clicking on the link at the beginning of the problem description. [I don't have example solutions to all of the problems yet. Working with lists In Scala, lists are objects of type List[A], where A can be any type. The solutions to the problems in this section will be in objects named after the problems (P01, P02, etc.). In many cases, there's more than one reasonable approach. P01 (*) Find the last element of a list. Example: scala> last(List(1, 1, 2, 3, 5, 8)) res0: Int = 8 P05 (*) Reverse a list. Examples: Related:  Scala

Setup - simple-build-tool - A build tool for Scala Trying SBT (Simple Build Tool) for compiling a simple (one file, perhaps two) Scala application with some dependencies (Apache Pivot) on Windows as specifying all the jars on the command line quickly becomes annoying... (I try to convert the tutorial files to Scala). Following the instructions here I have put the jar file in C:\Java\scala-2.8.0.final\misc and the sbt.cmd file in C:\Java\scala-2.8.0.final\bin Content of the latter: @echo offjava -Xmx512M -jar C:\Java\scala-2.8.0.final\misc\sbt-launch-0.7.4.jar %* As shown above, I use the current version, 0.7.4, supposed to support Scala 2.8. Project does not exist, create new project? Trying what is suggested, I answer s for a simple "hello world" setup (Quick Setup), perfect for my simple need (precisely a HelloScala? So I find the LocalScala page. Do I have to read the whole wiki before starting to experiment? So I look at BuildConfiguration and have a hint: I have to create a .scala file in the project/build directory.

Cassandra vs MongoDB vs CouchDB vs Redis vs Riak vs HBase comparison :: KKovacs (Yes it's a long title, since people kept asking me to write about this and that too :) I do when it has a point.) While SQL databases are insanely useful tools, their monopoly in the last decades is coming to an end. And it's just time: I can't even count the things that were forced into relational databases, but never really fitted them. (That being said, relational databases will always be the best for the stuff that has relations.) But, the differences between NoSQL databases are much bigger than ever was between one SQL database and another. In this light, here is a comparison of Open Source NOSQL databases Cassandra, Mongodb, CouchDB, Redis, Riak, RethinkDB, Couchbase (ex-Membase), Hypertable, ElasticSearch, Accumulo, VoltDB, Kyoto Tycoon, Scalaris, OrientDB, Aerospike, Neo4j and HBase: The most popular ones Redis (V3.2) Best used: For rapidly changing data with a foreseeable database size (should fit mostly in memory). For example: To store real-time stock prices. Cassandra (2.0)

Brushing Up on Computer Science Part 4, Algorithms » Victus Spiritus “An algorithm must be seen to be believed.”Donald Knuth How we ended up here It all began a few days ago with an email from a friend (thanks Denny). I was inspired to dust off my software engineering cap, and review a few choice topics in computer science. What better way to study than to write up a blog post sampling the materials of interest. The table of contents for this blog series: Algorithms In short, an algorithm is a recipe. A formula or set of steps for solving a particular problem. Understanding Strategies beats Memorizing Tactics Algorithms are well specified techniques for performing an unbounded variety of tasks (good luck learning all algorithms). There are broad patterns common to vastly separated problem spaces. A couple of the most famous divide and conquer techniques are the FFT and MapReduce (slides, web article). I first came across map reduce while reading a set of slides by Jeff Dean, Designs, Lessons and Advice from Building Large Distributed Systems. Quicksort

Real-World Scala: Dependency Injection (DI) ← Posted: 2008-10-06 In this second post in the Real-World Scala series I am going to discuss how to implement/achieve Depenency Injection (DI) in Scala. Scala is a very rich and deep language that gives you several ways of doing DI solely based on language constructs, but nothing prevents you from using existing Java DI frameworks, if that is preferred. Using the Cake Pattern The current strategy we are using is based on the so-called Cake Pattern. Note: I will try to explain things in steps which I refactor towards the final version (this is only to help with the understanding), so please wait with yelling: “This sucks!” First, let’s create a UserRepository (DAO) implementation. Here we could have split up the implementation in a trait interface and its implementation, but in order to keep things simple I didn’t see the need. Now let’s create a user service (also a dummy one, merely redirecting to our repository). Here you can see that we are referencing an instance of the UserRepository.

Stack Overflow Java EE 6 and Scala » Source Allies Blog Last weekend while pondering the question “Is Scala ready for the enterprise?” I decided to write a simple Java EE 6 app entirely in Scala, without using any Java. I had three main reasons for doing this: one was just to see how easy/difficult it would be to write everything in Scala (it was easy). Another was to document the process for others journeying down the same road (the entire project is on github). Finally, I wanted to identify advantages of using Scala instead of Java that are specific to Java EE apps (I found several). Background The specific app I created was an adaptation of the Books example from Chapter 10 of Beginning Java™ EE 6 Platform with GlassFish™ 3. Results As a baseline, I first created the example from the Book using Java (and put it on github). Next I rewrote the Java parts in Scala (and put it on github). First up, here’s Book.java: The Java version has 58 lines of completely useless getters & setters. Now let’s look at the Book entity in Scala: Conclusion

Great code is written twice (or more) | Redcode Evolving requirements It has now become common knowledge that you can’t write down all the requirements before you start the project. These requirements have to be written down in an evolutionary matter. In short cycles/sprints we build pieces of the program and also iteratively extract the latest requirements from our clients. This is all based on the principle of evolution. Evolving code! But why stop there? Wrong. In our current project, almost all important features have been rewritten from scratch multiple times. But… but… then you have to start all over again!? Wrong again! Again, like all things in life: To make something great, it has to go through multiple evolutionary iterations. Doing it twice, twice as slow? When I tell people that in my opinion all code needs to be written at least twice, they are afraid the project will take double the time. Good luck, keep rewriting and evolve your code!

Software Updates: Courgette The source code does not have this problem because all the entities in the source are symbolic. Functions don't get committed to a specific address until very late in the compilation process, during assembly or linking. If we could step backwards a little and make the internal pointers symbolic again, could we get smaller updates? Courgette uses a primitive disassembler to find the internal pointers. The non-pointer part is about 80% of the size of the original program, and because it does not have any pointers mixed in, it tends to be well behaved, having a diff size that is in line with the changes in the source code. We bring the pointers under control by introducing 'labels' for the addresses. How do we use this to generate a better diff? server: diff = bsdiff(original, update) transmit diff client: receive diff update = bspatch(original, diff) (The server would pre-compute diff so that it could be transmitted immediately) server: asm_old = disassemble(original) asm_new = disassemble(update)

Roundup: Scala for Java Refugees 13 Feb 2008 To be honest, I’m somewhat kicking myself for writing this post. As I’ve said many times: roundup posts are for people who are too lazy to write real content. I can’t tell you how many blogs I’ve come across which have a roundup-to-post ratio of easily 3:1. You know it’s a bad sign when sites start having roundups of their roundups… Meta-roundups aside, I decided (after much deliberation) that a single post linking to all six parts of the series would be useful to one or two people. Of course it’s always possible that you subscribe to my way of looking at things. Part 1: main(String[]) Introductory article giving motivation for learning Scala and some first steps to “get your feet wet” in the language. Part 2: Basic OOP Looking at Scala’s syntax in a little more detail. Part 3: Methods and Statics Scala’s method syntax is far too powerful to cover in a single post. Part 4: Pattern Matching and Exceptions Part 5: Traits and Types Part 6: Getting Over Java

scala « Mundo Funcional Pattern Matching y Case classes en scala Scala viene con el combinado de un soporte a pattern matching y a case clasess que ofrece una alternative muy flexible a la hora de establecer logicas basadas en opciones. En este post voy a tratar de hacer un pequeño resumen de estas características y su comparación con mecanismos anteriores en C/C++ y Java Para aquellos que venimos de C/C++ y Java estamos familiarizados con el bloque switch. Repasemos un poco, supongamos que temos el siguiente ejemplo: El valor del error medir el una corrientes electrica (mA) varía dependiendo del tipo de aparato que se use. Error aparato Analógico tiene un error relativo de 0.2 % de la medición Error aparato Digital tiene un error absoluto de 10 mA En este contexto tenemos una función: errorAbsoluto (in tipo: TipoAparato, in valor: Double) : Double que nos determina el error absoluto de una medición dependiendo del tipo de aparato. Su implementación en C/C++ podría ser algo asi: Pattern matching [2] Hasta la proxima!

Separating Code Coverage With Maven, Sonar and Jacoco We Recommend These Resources In this example I will expand upon my previous example of keeping your unit and integration tests in separate packages, and explain how to also produce code coverage statistics. For this I continue to use Maven, whilst adding Sonar and Jacoco to provide the code coverage.You can run the example below, but you will need to read the first article here to understand it. 1.1 Example Structure Here we have the typical maven structure and our new folder \src\integrationtest\java 1.2 Running the Example The full code is hosted at google code. svn co cd sonar mvn –Psonar,it clean install sonar:sonar You need to have sonar running. Go to sonar web interface and click on 'configure widgets' to add the IT coverage widget.You will also have to add the Jacoco plugin. You can see the Jenkins build here: You can see the Sonar build here

Donut math: how donut.c works -- a1k0n There has been a sudden resurgence of interest in my "donut" code from 2006, and I’ve had a couple requests to explain this one. It’s been five years now, so it’s not exactly fresh in my memory, so I will reconstruct it from scratch, in great detail, and hopefully get approximately the same result. This is the code and the output, animated in Javascript: At its core, it’s a framebuffer and a Z-buffer into which I render pixels. So how do we do that? To render a 3D object onto a 2D screen, we project each point (x,y,z) in 3D-space onto a plane located z’ units away from the viewer, so that the corresponding 2D position is (x’,y’). \begin{aligned} \frac{y'}{z'} &= \frac{y}{z} \\ y' &= \frac{y z'}{z}. So to project a 3D coordinate to 2D, we scale a coordinate by the screen distance z’. . and use that when depth buffering because: Now, how do we draw a donut, AKA torus? So we have a circle of radius R1 centered at point (R2,0,0), drawn on the xy-plane. ) and reuse them in the code. .

Related:  scala 4