A new web framework with an object-oriented design for “programmers who come from a Java background”.
A new web framework with an object-oriented design for “programmers who come from a Java background”.
A => Unit. That this function returns Unit rather than a meaningful type means that it must hardcode some action to take once the result (whose type is not even shown) is available. It is this unfortunate property that destroys any chance we have at combining actors in any sort of general way like we would in a typical combinator library. A, B or C?Unit => B, a pure function (A,B) => C, and an "output" side effect C => Unit. It makes perfect software engineering sense to decouple these components - and that is exactly what is done in purely functional programming.sort function, which sorts the input list in place. For this function, we have no input side effects. The pure core of this function is (conceptually) a sorting function that returns a new list. What is the output side effect? It is to rebind the name that the input list is bound to in the caller to the sorted version of the list. So if the caller were something like def foo(list: ArrayList[Int]): Foo = {
...
sort(list)
...
}then sort will rebind the name list to the sorted version of that list. Since list is itself a parameter of foo, this rebinding will occur in the caller of foo, and possibly its caller, all the way out to the place where that list was originally declared. The question is, should the sort function really be making the decision about whether to do this? If we let the sort function make this decision, we're allowing it to make an assumption about the caller, namely, that the caller no longer intends to maintain references to the unsorted version of the list (an assumption which, incidentally, is not even tracked by the type system).by Paul Chiusano (noreply@blogger.com) at March 12, 2010 06:11 AM
A => Future[B] and that therefore "actors" are composable, then I don't really have a problem with that (although, why call this model 'actors'? Why not call it 'functions from A => Future[B]' or 'the Kleisli arrow for futures'?). But if the actor model also includes the ability to asynchronously "send a message" to another arbitrary actor, and if the expression representing this message send does not evaluate to a future containing the result sent back by the receiving actor, then my subsequent arguments about the lack of composability still apply. The takeaway from my post, even if you think my definitions are bogus, shouldn't be "Aha!! Actors are okay! There is no issue with using them, even in stateful, non-composable ways".A => Unit can't possibly be RT unless they are literally the constant unit function.
If your program is purely functional, the compiler can assign threads to whichever chunks of calculation it wants to. Hence you don't need actors. Or any other form of explicit parallelism. The purpose of explicit synchronization is to manage the timing of side-effects in the presence of parallelism.
Future monad, which is explicit in the sense that you have decide when you are writing code in that monad, but implicit in that it only requires that you indicate dependencies between computations, not specify how those computations are scheduled out to threads, how many threads are used, etc. But I believe this breaks down for distributed computation, where the topology of the concurrency is a static or semi-static structure that must be under the control of the programmer. I've also found the monadic style doesn't work so great for "pipeline" parallelism. But more on that in a later post.by Paul Chiusano (noreply@blogger.com) at March 12, 2010 06:05 AM
“Yaketee is a message board with a twist. To post and read messages, you have to be on the same network as the people you’re exchanging messages with.”
“David Pollak maintains Lift, a Rails-like app framework for Scala. In this talk, he and Martin Odersky, author of Scala, live-code a 30-line, real-time, web-based chat application and discuss the Scala constructs that allow for such concise apps.”
/** something with a Guice module */
public interface HasGuiceModule {
GuiceModule module();
}
/**
* A simple test component using a Guice Module to inject its members
* when invoked by JUnit through the @Before annotation.
*
* If necessary, after the members injection, the subclass can use the localSetup method
* to add more initialization (like creating an initial customer) or more
* expectations (for mock objects)
*/
public abstract class TestComponent implements HasGuiceModule {
@Before
public void setup() {
inject();
localSetup();
expectations();
}
private void inject() {
module().inject(this);
}
protected void localSetup() {}
protected void expectations() {}
}
module() method definition for now:public class MockServer extends TestComponent {
@Inject
Connection connection;
@Inject
CustomerInterface customers;
@Inject
ProductInterface products;
@Inject
OrderInterface orders;
// do all the wiring when the members have been injected with Guice
@Override
protected void expectations() {
when(connection.getCustomersInterface()).thenReturn(customers);
when(connection.getProductsInterface()).thenReturn(products);
when(connection.getOrdersInterface()).thenReturn(orders);
}
protected GuiceModule module() { /** to be defined later */ }
}
public class Factories extends TestComponent {
// this server interface provides methods to individual objects: a customer
// a payment method, a customer address,...
@Inject CustomerInterface customers;
// this factory provide easy to use methods to create
// fully setup customers with delivery address, payment method,...
// it uses the CustomerInterface interface to do so
@Inject CustomerFactory customerFactory;
protected GuiceModule module() { /** to be defined later */ }
}
public class ConfirmationProcessorTest extends TestComponent {
// the class under test
@Inject ConfirmationProcessor processor;
// the standard order, it uses the OrderFactory and CustomerFactory to save and
// update the customer and order
@Inject CustomerOrder customerOrder;
@Test public void aConfirmationForAGoldCustomerMustDisplayStars() {
// a DSL for describing customer types
customerOrder.setCustomerType("Gold 5Y 4*");
confirmationMustContain("*******");
}
private void confirmationMustContain(String content) {
assertTrue(processor.
confirmationFor(customerOrder.customer()).contains(content));
}
protected GuiceModule module() { /** to be defined later */ }
}
The code above shows a classic JUnit4 class, with one method annotated with @Test. The nice things to notice are:module() method? How are GuiceModules defined? And why a GuiceModule and not a Guice,...,Module (i.e. com.google.inject.Module)? module() method is very straightforward. It just returns a GuiceModule which describes public ConfirmationProcessor extends TestComponent {
protected void module() {
return new ConfirmationProcessorModule();
}
}
// and
public ConfirmationProcessorModule extends GuiceModule {
// bindings go here
}
GuiceModule? Actually, a GuiceModule is mostly a regular com.google.inject.AbstractModule. It allows you to describe the bindings for a specific TestComponent. However, it is refinable, test-friendly and composable with other modules. public MockServerModule extends GuiceModule {
@Override protected void configure() {
// equivalent to bind(Customers.class).toInstance(mock(Customers.class))
// this binding declares that in every TestComponent using this GuiceModule
// the Customers interface will be a mock
mockAndBind(CustomerInterface.class);
}
}
public MockFactoriesModule extends GuiceModule {
@Override protected void configure() {
// in these bindings, we declare that the factories are
// going to use an in-memory representation of the database
// the job of a Mock database is to use the mock server interfaces
// to make as if a saved object was always returned when required
bind(CustomersDatabase.class).to(MockCustomersDatabase.class);
}
@Override protected Set<GuiceModule> modules() {
// add a MockServerModule to the list of dependent modules
return module(MockServerModule.class);
}
}public ConfirmationProcessorModule extends GuiceModule {
@Override protected List<Class<?>> mocks() {
return classes(DiscountCalculator.class);
}
@Override protected Set<GuiceModule> modules() {
return modules(CustomerOrderModule.class);
}
}new ConfirmationModule() {
@Override protected List<Class<?>> spies() {
return classes(ConfirmationProcessor.class);
}
}.remove(MockPrinterModule.class).add(RealPrinterModule.class)public Set<GuiceModule> getModules() {
Set<GuiceModule> result= new HashSet<GuiceModule>();
result.addAll(dependentModules); // a private list of added modules
result.addAll(modules()); // the ones declared by the subclass
for(GuiceModule m: modules()) {
result.addAll(m.getModules());
}
for(GuiceModule m: modulesToRemove()) {
result.removeAll(m.getModules());
}
result.add(this);
return result;
}GuiceModule#getModules() method adds or removes modules following all dependencies transitively (and recursively). The design is also kept voluntarily simple here. A Set makes sure that 2 "same" modules are never returned based on them being equal. And 2 modules are considered to be equal if they have the same class. public class MyTestWithAnOrder extends TestComponent {
// injecting the CustomerOrder builds an order which itself is injected
// forgetting that line would end up with an "empty" order
// (order.equals(new Order()))
@Inject CustomerOrder customerOrder
@Inject Order Order
public GuiceModule module() { return new CustomerOrderModule(); }
}You can also write: public class MyTestWithAnOrder extends CustomerOrder {
// the order member can be inherited and properly setup by the superclass
public GuiceModule module() { return new CustomerOrderModule(); }
}But here's a trick. If you declare the following binding in the CustomerOrderModule:public class CustomerOrderModule extends GuiceModule {
@Override protected void configure() {
...
bind(Order.class).toInstance(new Order());
bind(CustomerOrder.class).toInstance(new CustomerOrder);
...
}
}
// given that CustomerOrder looks like
public class CustomerOrder extends TestComponent {
@Inject Customer customer;
@Inject Order order;
@Inject OrderFactory orderFactory;
// this is where, as a post-construct step, the order object gets fully setup
@Inject
protected void localInit() {
orderFactory.saveAsStandardOrder(order);
}
public void GuiceModule module() { return new CustomerOrderModule(); }
}
Then, you can just access the order dependency in your test without having to reference the CustomerOrder TestComponent: public class MyTestWithAnOrder extends TestComponent {
// it just works (tm)
@Inject Order Order
public GuiceModule module() { return new CustomerOrderModule(); }
}autoGet() methods. Customer object and use mocks to have it returned when someone calls getCustomer(id). But you may actually not really care about which customer it really is. So why not go one step further with an autoGet() method? autoGet() on the factory will just set-up the mock object representing the CustomerInterface on the Server so that every time a customer is requested with an id, you simply create one on the fly and return it! (see here to see how to do it with Mockito).a composable continuation, delimited continuation or partial continuation, is a "slice" of a continuation frame that has been reified into a function.
import scala.continuations._
import scala.continuations.ContextControl._
object SimpleCont {
def main(args : Array[String]) : Unit = {
val result = reset {
1 + shift { k => k(k(5)) } + 1
}
Console.println(result)
}
}
reset {
1 + shift { k => k(k(5)) } + 1
}
val reifiedFunction = { shiftVal1 : Int =>
1 + shiftVal1 + 1
}
object SimpleCont {
def main(args : Array[String]) : Unit = {
val result = reset {
1 + shift { k => k(k(5)) } + 1
}
Console.println(result)
}
}
object SimpleCont {
def main(args : Array[String]) : Unit = {
val reifiedFunction = { shiftVal1 : (Int => Int)
1 + shiftVal1 + 1
}
val result = reifiedFunction(reifiedFunction(5))
Console.println(result)
}
implicit def reflectiveList[A](xs:List[A]) = new {
def reflect[B]() : A @cps[List[B], List[B]] = shift { k:(A => List[B]) =>
xs.flatMap(k)
}
}
reset {
val left = List("x","y","z")
val right = List(4,5,6)
List((left.reflect[(String,Int)], right.reflect[(String,Int)]))
}
}
// result: cartesian product
reset {
val left = List("x","y","z")
val right = List(4,5,6)
List(Tuple2(
left.reflect[Any],
right.reflect[Any]
))
}
reset {
val left = List("x","y","z")
val right = List(4,5,6)
List(Tuple2(
shift { k:(A => C[B]) =>
left.flatMap(k)
},
shift { k:(A => C[B]) =>
right.flatMap(k)
}
))
}
val reified : = { (shift1, shift2) =>
List(Tuple2(
shift1,
shift2
))
}
val reified : (String, Int) => List[Any] = { (shift1, shift2) =>
List(Tuple2(
shift1,
shift2
))
}
//Original reset was here...
val left = List("x","y","z")
val right = List(4,5,6)
left.flatMap( l => right.flatMap(r => reified(l,r))
//Original reset was here...
val left = List("x","y","z")
val right = List(4,5,6)
val reified1 : (String => List[Any]) = { shift1 =>
val reified2 : (Int => Any) = { shift2 =>
Tuple2(shift1,shift2)
}
right.flatMap(reified2)
}
left.flatMap(reified1)
HAI!
O
MY!
trait Resource[+R] {
def flatMap[U](f : R => U) : U
def reflect[B]() : R @cps[B,B] = shift { k : (R => B) => flatMap(k) }
}
def resource[R <: Closeable](acquire : => R) = new Resource[R] {
override def flatMap[U](f : R => U) : U = {
val x = acquire
try {
f(x)
} finally {
System.out.println("Closing Resource!")
x.close()
}
}
}
def reflect[A <: InputStream](input : A) = new {
def each_line[B] : String @cps[B,List[B]] = shift { k : (String => B) =>
val b = new BufferedReader(new InputStreamReader(input))
var line = b.readLine
var list = ListBuffer[B]()
while(line != null) {
list += (k(line))
line = b.readLine
}
list.toList
}
}
reset {
val input = resource(new FileInputStream("test.txt")).reflect[Any] //We cheat on the return value here!
val line = invert(input).each_line[Int] //We need to know the continuation returns an Int Here!!!
System.out.println(line)
line.size
}
val input = new scala.io.magic.File("test.txt")
for {
stream <- file.managedInput
line <- input.lines
} yield line.size
You'll notice a few similarities (in my made up library). For-expressions are another area in scala where you're reifing portions of the code into closures and passing them to flatMap blocks. However, delimited continuations open the doors to way more than flatMap. Let's go back to that typing issue though.If you remember, I was returning Any because I was being lazy with my type annotations when reflecting the input stream. Let's use the correct annotation:reset {
val input = resource(new FileInputStream("test.txt")).reflect[List[Int]]
val line = invert(input).each_line[Int] //We need to know the continuation returns an Int Here!!!
System.out.println(line)
line.size
}
So... what do these type annotations mean? In the case of the resource's reflect method, the type annotation is the ultimate result from the reset call (i.e. the result of the reified continuation) because of how we defined flatMap on Resource. The type annotation for each_line describes the type the resulting List of processed lines should contain... i.e. the result of the last portion of the continuation. If we were to hand-code this reset piece we'd have: val rcont1 : (FileInputStream => List[Int]) = { inputStream =>
val rcont2 : (String => Int) = { line =>
System.out.println(line)
line.size
}
val b = new BufferedReader(new InputStreamReader(inputStream))
var line = b.readLine
var list = ListBuffer[B]()
while(line != null) {
list += (rcont2(line))
line = b.readLine
}
list.toList
}
resource(new FileInputStream("test.txt")).flatMap(rcont1)
by J. Suereth (noreply@blogger.com) at March 11, 2010 03:56 AM
by Henrik Huttunen (henrik.huttunen@gmail.com) at March 10, 2010 07:15 PM
Also a nice illustration of 2.8 collection improvements.
This year the Scala team will apply for the Google Summer of Code program to work with enthusiastic students on challenging Scala projects! Google invites students to come up with interesting, non-trivial problems for their favourite open-source projects, and work on them over the summer. Aside from the satisfaction of solving challenging problems, students get paid for their work.
We have collected a list of project ideas for you; we expect students to explore these ideas in much more detail, adding their own suggestions and plans on how to proceed. Find all the details about Scala and the Google Summer of Code on this page.
The best post on the internet got some sweet linkage again this week. You know, the one where Scala is too complex because you can express the sum of a list of numbers like so:
def sum(nums: List[Int]) = (0 /: nums) { _ + _ }
In the intervening years since that expression prompted a ‘verdict’ that Scala was too difficult for us regular folks, a lot of us have written a heck of a lot of Scala. We had to make implicit.ly just to keep up with the flow of Scala software that people are publishing these days. The pump is primed and the machinery has finally come to life. It’s an exciting time! For some.
But since it’s come up, let’s review that old /: scarecrow. What makes him so perplexing to newcomers? Some have blamed the use of non-letters in the name. Okay then, how much clearer would Joe BeanFactory find this definition?
def sum(nums: List[Int]) = (nums foldLeft 0) { _ + _ }
Not much really! Well, maybe the problem is the infix notation?
def sum(nums: List[Int]) = nums.foldLeft(0) { _ + _ }
Yeah, I don’t know. By this point our rhetorical corporate programmer has gone out for coffee. Perhaps he will be back later to decide which programming languages we’re all supposed to use for his convenience. Maybe he would rather express things like 1 + 1 as 1.plus(1) —or, maybe he just doesn’t give a Dilbert about orthogonality.
But seriously guys, I don’t think it’s the infix notation or the permitting of symbolic characters in syntactic symbols that make applications of /: difficult to grok at first. It’s the blessed currying. Setting off the first function application with parentheses prevents one’s uninitiated mind from cheaply translating it to a familiar series of parameters. Instead you have to recognize that the first function application returns a second function, which is applied to another set of parameters. It’s trippy.
Truth be told, this perplexed me at the time. But instead of rejecting the language for supporting functional constructs beyond my experience, I decided to keep learning—and I’m happy with how that has worked out. So it’s interesting that two years later, this particular functional freak-out has been ‘cited’ to brand Scala as overly complex (Perl-y) while a second thread of spite bemoans Scala’s insufficient promotion of currying.
It’s simple, you see. The currying in Scala makes innocent enterprise developers cry in their frappuccinos, while similar encounters in OCaml inspire a rapturous session of functional mind-blowing.
Well. At least you can learn Scala at your desk.
by James Iry (noreply@blogger.com) at March 08, 2010 03:40 PM
Jam packed with a schedule of advanced research and technical talks by some of the most knowlegable experts in the industry. Jam packed with Scala community know-how, over 80 people already registered. And jam packed with opportunities to meet and talk to other Scala developers. Scala Days 2010, 15-16 April, EPFL, Switzerland.
The full schedule of sessions, presenters and abstracts is now available. It is the time to take a look, decide what to see and get organised to come! At Scala Days you'll have a ball! Learn about the latest research, see how smart people are applying it in serious commercial applications, talk over your ideas, your company projects with other top notch people, people like Chris Conrad (from LinkedIn), Nathan Hamblen (SPDE contributor), Jorge Ortiz (Lift web framework committer) , Kunle Olukotun (Director Stanford Pervasive Parallelism Lab) Miles Sabin (Eclipse PlugIn), David Copeland (Industry Consultant), Heiko Seeberger (ScalaModules), Jonas Bonér (AKKA) and Josh Suereth (Maven-scala-plugin and more), and of course the entire EPFL Scala research group with Martin Odersky.
def scalaLibrarySum(a : Array[Int]) = a.map(i => i * 3 + 7).filter(i => (i % 10) == 0).foldLeft(0)(_ + _)
def mapFilterSumLoop(a : Array[Int]) = {
var i = 0
var r = 0
while (i < a.length) {
val v = a(i) * 3 + 7
if ((v % 10) == 0)
r += v
i += 1
}
r
}
// Specialized Function1
trait Fn1[@specialized I, @specialized O] {
def apply(a : I) : O
}
// Specialized Function2
trait Fn2[@specialized I1, @specialized I2, @specialized O] {
def apply(a1 : I1, a2 : I2) : O
}
// Specialized iterator
trait SIterator[@specialized T] {
def hasMore : Boolean
def current : T
def next()
}
class IntArrayIterator(a : Array[Int], var index : Int, endIndex : Int) extends SIterator[Int] {
def next() = index += 1
def current = a(index)
def hasMore = index < endIndex
}
// Optimally this would be: class FilterIterator[@specialized T](iter : SIterator[T], pred : Fn1[T, Boolean]) extends SIterator[T]
class FilterIterator(iter : SIterator[Int], pred : Fn1[Int, Boolean]) extends SIterator[Int] {
def hasMore = iter.hasMore
def next() = {
iter.next()
findNext()
}
def findNext() = {
while (iter.hasMore && !pred(iter.current))
iter.next()
}
def current = iter.current
findNext()
}
// Optimally this would be: class MapIterator[@specialized U][@specialized T](iter : SIterator[T], fn : Fn1[T, U]) extends SIterator[U]
class MapIterator(iter : SIterator[Int], fn : Fn1[Int, Int]) extends SIterator[Int] {
def next() = iter.next()
def current = fn(iter.current)
def hasMore = iter.hasMore
}
def fold[@specialized T, @specialized U] (iter : SIterator[T], fn : Fn2[U, T, U], v : U) = {
var r = v
while (iter.hasMore) {
r = fn(r, iter.current)
iter.next()
}
r
}
def mapFilterSum(a : Array[Int]) = {
val filter = new Fn1[Int, Boolean] {def apply(a : Int) = (a % 10) == 0}
val map = new Fn1[Int, Int] {def apply(a : Int) = a * 3 + 7}
val s = new FilterIterator(new MapIterator(new IntArrayIterator(a, 0, a.length), map), filter)
fold(s, new Fn2[Int, Int, Int] {def apply(a1 : Int, a2 : Int) = a1 + a2}, 0)
}
Loop: (4990,-423600172)
Loop with intermediate arrays: (6690,-423600172)
Specialized iterators: (5367,-423600172)
Scala array: (46444,-423600172)
Scala view: (39625,-423600172)
Scala stream: (63210,-423600172)
by Jesper Nordenberg (noreply@blogger.com) at March 07, 2010 01:02 PM
Getting started with any programming language is a daunting task, let alone getting your workstation in a state to create a non-trivial application. I spent a few days reading and trying many Scala tools and libraries. I use some of my findings in this screencast.
This screencast covers how to create a Scala console-based project. I use the simple-build-tool (sbt) to compile, run, test and then eclipsify a project. I briefly cover where to put source code, tests and how to use Eclipse to edit and debug the project. Click here to view to screencast.
>\ for post and put>+> operator, to use more than one handler against the same request with overlapping scopes>--> operator in dispatch-mime, to support Riak link-walking and map-reduce
>--> operator in dispatch-mime, to support Riak link-walking and map-reduce
I am outraged at the SF Muni and their adoption of the TransLink
card. Soon, there are certain bus lines that will only accept the
TransLink card during rush hour... you won't be able to ride the bus
except with one of these evil devices.
So, what's my outrage?
I spent most of today trying to obtain a TrankLink card for my
kids. I read on the TransLink site that the youth cards
had to be obtained in person rather than at the normal retail
outlets.
So, I took my kids downtown figuring I could buy a card at a Muni
station, but no dice. Most of the folks in the Muni stations had
no clue. Finally, somebody pointed me to Golden Gate Transit in
the Ferry Building, so off we went to the Ferry Building.
We find the right booth to buy the pass. Now, my kids are in
kindergarten. There's no question that they are youths and are
elegible for youth discounts. In fact, most Muni drivers say,
"These kids look too young to pay." My response is, "Muni rules
say that 5 year olds pay and we follow rules in our family."
So, I ask for 2 youth passes. The woman behind the counter
says, "give me their birth certificates and we'll give you the youth
passes." I say, "that's a joke, right? Look at them, do
they look anywhere near 16 or 18 or whatever the cutoff age is?"
She responds, "Our policy is that we only issue youth cards with a
birth certificate."
We've had to show the kids' birth certificates for their social
security cards and for entrance to school. We did not have to
produce birth certificates for library cards, health insurance, so I'm
wondering what is going on here. I ask for a supervisor.
I talk to the supervisor and he tells me, "It is our policy that you
need a birth certificate to obtain a youth TransLink card." Me:
"Why? Do these kids look like they're too old for the
card?" Him: "We bond the birth certificate to the card to avoid
fraud." Me: "You what?" Him: "We make sure that the
discount card is associated with the person." Me: "So, you're
telling me that in order to get a discount, you guys are going to track
the movements of my kids throughout the TransLink system? How is
this supposed to reduce fraud?" Him: "That's our policy,
sir." Me: "Your policy is Orwellian and there's no way I'm
letting you associate my kids' public transportation usage with their
birth certificate. Instead of trying to buy cards for the kids,
I'm going to burn mine."
So, we walk away. The supervisor comes running after me.
"Sir, your kids look young enough that they don't need to pay a fair
anyway." Me: "First, they have to pay on the SF Muni and we
follow the rules so we pay. Second, giving me a 'free-be' today
don't mitigate your Big Brother policy of tracking my kids
where-abouts." Him: "I'm just trying to be helpful." Me:
"If you want to be helpful, go back to your boss and explain to him
that this is the United States and we move freely in this country."
My kids asked me why I was cranky. I said, "Because the bad
people want to know where you go." Kids: "We're not going
anywhere bad, so why don't we want people to know where we've
gone?" Me: "It is our right as Americans to come and go as we
please. It's our right to be private. But more importantly,
historically, once the government starts tracking their citizens,
especially their children, they will find a way to use the information
against you. It's not that we have anything to hide, it's that
any time people want to always know, they are up to no good... they are
bad people."
So, we walk through the Ferry Building and I see a guy with an EFF hat.
Now, this is San Francisco, so it's not unexpected to see some guy
sporting an EFF hat. I go up to him and say, "Are you a member of
the EFF? I was one of the first donors to the EFF so don't get
freaked." He says, "Yes." I say, "The TransLink folks want
my kids' birth certificates in order to get a youth TransLink card and
they bond the birth certificate to the card so they track the kid's
movement throughout their system." His jaw dropped to the
ground. We shared a brief moment of liberal outrage and my kids
and I went on our way.
When I got home, I checked the TransLink site. There is no
mention of requiring a birth certificate to obtain a youth pass.
I called the TransLink customer service line and they did verify that a
birth certificate is required.
First, TransLink is hiding the fact that a birth certificate is
required. It's not on their public web site although it is
mentioned in a press release. Why are they hiding this
information? Do they think that if they don't publish it on their
web site that somehow it'll make it okay?
Second, TransLink is managed by the Metropolitan
Transportation Commission, but this is not mentioned anywhere on
the TransLink web site and is only mentioned once in the TransLink
cardholder "license agreement". Why is the MTC hiding?
Third, if the MTC is a governmental body, where was the public
hearing and the public comment request relating to requiring a birth
certificate and bonding that information to youth passes?
Forth, what great problem are they looking to solve by associating a
card with a person? What kind of failures is the current youth
(and elderly) pass mechanism (a different colored pass) justify bonding
my child's birth certificate to their transit card and track my
children's comings and goings?
So, I am outraged. I will burn my TransLink card and until
this Orwellian, KGB-esq policy of requiring a birth certificate to get
a youth TransLink, I will not in any way participate in the TransLink
system. I urge you to do the same.
by David Pollak (nospam@example.com) at March 06, 2010 06:06 AM
In Scala 2.8, using the builder pattern is no longer necessary (or the most optimal solution) in many cases, as Scala 2.8 adds support for named and default parameters.
I’ll give an example of this based on ScalaBox2D. In the Box2D object model, physics Bodies are defined mostly by a set of Fixtures, which in turn are defined by a Shape, density, friction, restitution and some other parameters.
In the Scala 2.7 version of ScalaBox2D, there were mutable fixture definitions, which were used by the engine to create the actual fixtures. The user code only worked with definitions, through an internal DSL that looked something like this (note: all code examples are simplified for clarity):
body {
box(halfWidth, halfHeight) density 1 friction 0.3f restitution 0
computeMassFromShapes
}
For the DSL implementation, I used simple builders which left values to defaults if not specified:
def box(halfW: Float, halfH: Float) = new FixtureBuilder(FixtureDef(PolygonDef.box(halfW, halfH)))
class FixtureBuilder(defn: FixtureDef) {
def userData(userData: AnyRef) = { defn.userData = userData; this }
def material(material: Material) = { defn.apply(material); this }
def friction(friction: Float) = { defn.friction = friction; this }
def restitution(restitution: Float) = { defn.restitution = restitution; this }
def density(density: Float) = { defn.density = density; this }
def filter(filter: FilterData) = { defn.filter = filter; this }
def sensor(isSensor: Boolean) = { defn.isSensor = isSensor; this }
def define = defn
}
The FixtureDefs are mutable mostly to simplify the builder. In Scala 2.8, I can use named and default parameters, and drop some more lines of code by not having builders at all. As a bonus, I can easily make the definitions immutable.
def fixtures(fd: FixtureDef*) {...}
val fixture = FixtureDef // a shorthand to the companion object of FixtureDef
val box = BoxDef // a shorthand to a BoxDef object that creates PolygonDefs
case class FixtureDef(
shapeDef: ShapeDef,
/** The friction coefficient, usually in the range [0,1]. */
friction: Float = 0.2f,
/** The restitution (elasticity) usually in the range [0,1]. */
restitution: Float = 0f,
/** The density, usually in kg/m^2. */
density: Float = 0f,
/** A sensor collects contact information but never generates a collision response. */
isSensor: Boolean = false,
/** Contact filtering data. */
filter: FilterData = FilterData.Default,
/** Use this to store application specific fixture data. */
userData: AnyRef = null
)
As you can see, the FixtureDef is now a case class with immutable parameters that have default values. Previously it looked very similar, but had only one parameter (ShapeDef) and all fields were mutable. The usage of the “DSL” now becomes a little bit more verbose (maybe I shouldn’t even call it a DSL any more) but I think it also becomes easier to understand for someone who knows the language but not the library, due to less moving parts and using built-in features instead of more code:
body {
fixtures(
fixture(box(halfWidth, halfHeight), density = 1, friction = 0.3f, restitution = 0)
)
computeMassFromShapes
}
Deleting code while maintaining functionality always makes me glad and this is one of those cases. I guess there may be some more complex cases where builders may still work better, but for simple things like the above example, I really like the named and default arguments feature.
Note: moving ScalaBox2D to Scala 2.8 is still a work in progress for me and there may be some further changes to this “DSL” as well.

def f(x: {val name: String; val age: Int}) = {import x._
println(name + " is " + age + " years old")
f(new {val name = "Anthony"; val age = 5})case class Name(name : String)
case class Age (age : Int)
def g(x: Name, y: Age) = {import x._, y._
println(name + " is " + age + " years old")
g(Name("Tim"), Age(2))
object Test extends Application{
def f(x: {val name: String; val age: Int}) = {
import x._
println(name + " is " + age + " years old")
}
f(new {val name = "Anthony"; val age = 5})
case class Name(name : String)
case class Age (age : Int)
def g(x: Name, y: Age) = {
import x._, y._
println(name + " is " + age + " years old")
}
g(Name("Tim"), Age(2))
}
val age = 8
val name = "Jim"
f(age, name)
f(new {val age = 8; val name = "Jim"}) isn't that bad at all. Neither the case class equivalent. If you have many arguments to pass, calling with single argument per line looks nice:f(new { val age = 8
val name = "Jim"
val hobby = "blogging" })by Henrik Huttunen (henrik.huttunen@gmail.com) at March 03, 2010 06:47 AM
This repository contains various plugins for the SBT build tool:
Remember how everybody dutifully assumed that Apple was patenting everything from Minority Report as a defense measure against, you know, ‘other’ patent trolls? Well it turns out that is not the case. They’re going to preemptively file suit to impede their competition, because they can. This is how things work.
That feature you’ve been clicking around for on github exists, now!
Slowly but surely becoming a command line for Scala.
Click on their PDF link for beautiful aerial photos and session details!
Nikita Ivanov, Founder and CEO of GridGain will be presenting "Cloud Computing with Scala and GridGain" in the "New Cloud!" track at the The ServerSide Java Symposium, March 17-19, 2010, Caesars Palace, Las Vegas. This will be the first showing of the GridGain v3.0 code base in a practical hands-on session where he will show you how to use Scala with GridGain’s cloud development platform to create simple and productive cloud computing platforms. TSSJS will have lots of informative sessions for you and the added bonus of being able to listen to James Gosling, the father of Java, keynote speech too.
public class RealPayment implements Payment {
@Inject
public RealPayment(
CreditService creditService, // injected
AuthService authService, // injected
@Assisted Date startDate, // caller to provide
@Assisted Money amount); // aller to provide
}
...
}
Provider<Factory> ..bind(PaymentFactory.class).toProvider(
FactoryProvider.newFactory(
PaymentFactory.class, RealPayment.class));
FactoryProvider maps the create() method's parameters to the corresponding @Assisted parameters in the implementation class' constructor. For the other constructor arguments, it asks the regular Injector to provide values.AssistedInject solves is to finalize (close) some of the parameters at the module level to be provided by the injector, while keeping the abstraction open for the rest to be provided by the caller.trait CreditService
trait AuthService
case class RealPayment(creditService: CreditService,
authService: AuthService,
startDate: Date,
amount: Int)
val rp = RealPayment( //..
RealPayment.apply( //.. that gets called implicitly. But you know all that .. right ?PayPal as the CreditService implementation, so that the users don't have to pass this parameter repeatedly - just like the injector of your favorite dependency injection provider. I can do this as follows in a functional way and pass on a partially applied function to all users of the module .. scala> case class PayPal(provider: String) extends CreditService
defined class PayPal
scala> val paypalPayment = RealPayment(PayPal("bar"), _: AuthService, _: Date, _: Int)
paypalPayment: (AuthService, java.util.Date, Int) => RealPayment = <function>
paypalPayment as a function from (AuthService, java.util.Date, Int) => RealPayment. The underscore acts as the placeholder that helps Scala create a new function object with only those parameters. In our case the new functional takes only three parameters for whom we used the placeholder syntax. From your application point of view what it means is that we have closed the abstraction partially by finalizing the provider for the CreditService implementation and left the rest of it open. Isn't this precisely what the Guice injector was doing above injecting some of the objects at module startup ?paypalPayment with only the 3 parameters that are still open ..scala> case class DefaultAuth(provider: String) extends AuthService
defined class DefaultAuth
scala> paypalPayment(DefaultAuth("foo"), java.util.Calendar.getInstance.getTime, 10000)
res0: RealPayment = RealPayment(PayPal(foo),DefaultAuth(foo),Sun Feb 28 15:22:01 IST 2010,10000)
AuthService as well in addition to freezing PayPal as the CreditService. One alternative will be to define another abstraction as paypalPayment through partial application of RealPayment where we close both the parameters. A better option will be to reuse the paypalPayment abstraction and use explicit function currying. Like ..scala> val paypalPaymentCurried = Function.curried(paypalPayment)
paypalPaymentCurried: (AuthService) => (java.util.Date) => (Int) => RealPayment = <function>
DefaultAuth implementation ..scala> val paypalPaymentWithDefaultAuth = paypalPaymentCurried(DefaultAuth("foo"))
paypalPaymentWithDefaultAuth: (java.util.Date) => (Int) => RealPayment = <function>
PayPal for CreditService and DefaultAuth for AuthService. Like Guice we can have hierarchies of modules that injects these settings and publishes a more specialized abstraction to downstream clients.by Debasish (ghosh.debasish@gmail.com) at March 01, 2010 05:59 AM
trait BaseActor extends Actor {
def makeMessageHandler() : PartialFunction[Any,Unit] = {
case x => //Unhandled message, assume design flaw!
error("Unknown message: " + x)
}
}
trait FinalActor extends BaseActor[T] {
lazy val messageHandler = makeMessageHandler()
override def act() {
Actor.loop {
react messageHandler
}
}
}
case class Ping()
case class Pong()
trait PingPongBehavior extends BaseActor {
def makeMessageHandler() : PartialFunction[Any,Unit] = {
val myBehavior : PartialFunction[Any,Unit] = {
case Ping() => sender ! Pong()
}
return myBehavior orElse super.makeMessageHandler()
}
}
case class Shutdown()
trait RemoteControlBehavior extends BaseActor {
def makeMessageHandler() : PartialFunction[Any,Unit] = {
val myBehavior : PartialFunction[Any,Unit] = {
case Shutdown() => Actor.exit
}
return myBehavior orElse super.makeMessageHandler()
}
}
val myActor = new PingPongBehavior with RemoteControlBehavior with FinalActor
myActor.start
class UserWorker(...) extends WorkerImpl[..., UserMsg](...) {
/**
* handle the Follow message
*/
def doFollow(msg: Follow) {
...
}
}
Followclass must be a subclass of
UserMsgas Goat-Rodeo is also strongly typed. Because
doFollowreturns Unit, goat-rodeo knows that there is no return expected with this message. If you'd like to handle different messages, simple use method overloading. The best part, if we'd like to use OO inheritance to compose behavior, we can do so directly now...
class UserWorkerPlus(...) extends UserWorker(...) {
/**
* handle the Follow message
*/
def doFollow(msg: Follow) {
println("ZOMG!!!!!!!!!!!!!!!!!!")
super.doFollow(msg)
}
}
import scala.actors.Actor
import scala.actors.Channel
class ChanneledActor[T](f : PartialFunction[T,Unit]) extends Actor {
val typedChannel = new Channel[T](this)
def act() {
Actor.loop {
typedChannel react f
}
}
}
def makeActor[T, U](f : PartialFunction[T,U]) : Channel[T] = {
val a = new ChanneledActor(f andThen ( x => () )) //Ignore results...
a.start
a.typedChannel
}
scala> makeActor[Int,Unit] { case x : Int => println("HAI") }
res3: scala.actors.Channel[Int] = scala.actors.Channel@154f77b
scala> res3 ! "HAI"
<console>:10: error: type mismatch;
found : java.lang.String("HAI")
required: Int
res3 ! "HAI"
^
scala> res3 ! 5
scala> HAI
by J. Suereth (noreply@blogger.com) at February 28, 2010 03:47 PM
Or more fully “Ruby, Scala, Geo, NLP, Ad Serving & Optimization”. Are you their next “Superstar Software Engineer”???
import org.scalatest.fixture.FixtureFunSuite
import org.scalatest.Tag
class WickedCoolTest extends FixtureFunSuite{
type FixtureParam = Map[String,Any]
override def withFixture(test: OneArgTest) {
test(test.configMap)
}
test("1", Tag("dood1")){ conf => println("dood1: " + conf) }
test("2", Tag("dood2")){ conf => println("dood2: " + conf) }
test("3", Tag("dood3")){ conf => println("dood3: " + conf) }
}
test-only WickedCoolTest
test-only WickedCoolTest -- -n dood1
test-only WickedCoolTest -- -n "dood1 dood2"
test-only WickedCoolTest -- -l dood2
test-only WickedCoolTest -- -l "dood2 dood3"
test-only WickedCoolTest -- -Danswer=42
test-only WickedCoolTest -- -Danswer=42 -DrealAnswer=54
test-only WickedCoolTest -- -n "dood dood2" -Dhey=you -Dm=f
> test-only *IntParallelArrayCheck -- -s 5000
...
[info] == scala.collection.parallel.mutable.IntParallelArrayCheck ==
[info] OK, passed 5000 tests.
override def testOptions =
super.testOptions ++
Seq(TestArgument(TestFrameworks.ScalaCheck, "-s", "5000"))
override def testOptions =
super.testOptions ++
Seq(TestArgument(TestFrameworks.ScalaTest, "-n", "fast"))
lazy val blah = singleTestTask("blah.blah.Blah")
private def singleTestTask(className: String) = task { args =>
defaultTestTask(TestFilter(_ == className) ::
testOptions.toList ::: ScalaTestArgs(args))
}
private def newScalaTestArg(l: String*) =
TestArgument(TestFrameworks.ScalaTest, l:_*)
private def ScalaTestArgs(args: Seq[String]): List[TestArgument] = {
def KVArgs(args: Seq[String]): TestArgument =
newScalaTestArg(args.map("-D" + _):_*)
def tagsFromArgs(tags: Seq[String]): List[TestArgument] = {
if (tags.isEmpty) Nil else
List(newScalaTestArg("-n", tags.mkString(" ")))
}
val (kvs, tags) = args.partition(_.contains("="))
KVArgs(kvs.toSeq) :: tagsFromArgs(tags.toSeq)
}
lazy val testSlow =
runSubclassesOf("org.nlogo.util.SlowTest")
lazy val testFast =
runEverythingButSubclassesOf("org.nlogo.util.SlowTest")
private def runSubclassesOf(className: String) = {
val subclass: Boolean => Boolean = x => x
subclassTest(className, subclass)
}
private def runEverythingButSubclassesOf(className: String) = {
val notSubclass: Boolean => Boolean = x => ! x
subclassTest(className, notSubclass)
}
private def subclassTest(className: String,
subclassCheck: Boolean => Boolean) = task {
args =>
lazy val jars =
testClasspath.get.toList.map(_.asURL).toArray[java.net.URL]
lazy val loader =
new java.net.URLClassLoader(jars,buildScalaInstance.loader)
def clazz(name: String) = Class.forName(name, false, loader)
lazy val superClass = clazz(className)
def filter =
TestFilter(c =>
subclassCheck(superClass.isAssignableFrom(clazz(c))))
defaultTestTask
(filter :: testOptions.toList ::: ScalaTestArgs(args))
}
by Jack Cough (noreply@blogger.com) at February 24, 2010 05:59 PM
Peter will talk about … The work he’s been doing to integrate Scala into The Play Framework … And his very own Pinky, a REST/MVC glue web framework built on top of Guice and Guice Servlet 2.0
Right after Apple made us ridicule their sorry quest for a mobile “bring-up” loser, Phil Schiller has gone and blabbed a bunch of 1984 crap to the Times, which he foreshadowed back in November. It’s awesome.
See, just over the last few weeks the world has gotten really Naughty. Schiller himself has blushed at
an increasing number of apps containing very objectionable content.
Oh my! Let’s just hope Schiller was not forced to evaluate each and every one, in private. Apparently this is a Unique Crisis:
It came to the point where we were getting customer complaints from women who found the content getting too degrading and objectionable, as well as parents who were upset with what their kids were able to see.
Now hold on a sec, Mr. Schiller. Women have been known to disagree with each other on many things, including what is too degrading (?) or objection-able. It’s a little iffy to completely ban products based on what you say the women say. And those parents, maybe you should tell them about the famous “parental controls” you now build into everything?
We obviously care about developers, but in the end have to put the needs of the kids and parents first.
Much like it has always been necessary to ban racy items from bookshelves, computers, and the internet because some anonymous prude in the employ of a private business was offended/aroused.
But what about Sports Illustrated’s beloved mainstream pr0n—which (some) women have been objecting to for ages—is there some kind of special, or double, standard in place to protect our big old-media brands?
The difference is this is a well-known company with previously published material available broadly in a well-accepted format.
Well that’s a relief. S.I. is just appropriately degrading to women.
On the other hand if you want a software platform that isn’t run like a bought-off nursery, there are alternatives.
// Dynamically create a DummyServiceToMakeCodeTransactional bean and register with spring
DefaultListableBeanFactory autowireCapableBeanFactory = (DefaultListableBeanFactory) getApplicationContext().getAutowireCapableBeanFactory();
AbstractBeanDefinition beanDefinition =
BeanDefinitionBuilder.rootBeanDefinition(
DummyServiceToMakeCodeTransactional.class.getName()).getBeanDefinition();
autowireCapableBeanFactory.registerBeanDefinition("DummyService", beanDefinition);
DummyServiceToMakeCodeTransactional bean = (DummyServiceToMakeCodeTransactional)
getApplicationContext().getBean("DummyService");
by Tim Azzopardi (noreply@blogger.com) at February 23, 2010 12:08 PM
The job posting from the Cupertino, CA, company specifically calls for an engineering manager to handle “platform bring-up.” In the job description, Apple states that it’s looking for a manager “to lead a team focused on bring-up of iPhone OS on new platforms.” It seems like Apple wants some outside talent with very strong technical experience, especially when it comes to bringing software onto multiple hardware devices.
Whatever a “bring-up” is, this job posting is weird because Apple is supposed to have the next decade specked out already, if not in product testing. We (consumers) learn about the future of computing at Apple events, when they decide to tell us. Our 2015 portable computers will be descendants of Apple’s “iPad” invention, like those copy-cat props in Avatar and Minority Report.
But this job posting would imply that Apple is in a competitive marketplace where other companies have ideas, too. That open mobile platforms may be on the verge of a cambrian explosion of unexpected, unplanned, useful devices that will be difficult to fight off with a platform that is locked down in both hardware (old news!) and software (evil news!). That the world hasn’t been standing still in the two years that the iPhone has … grown. (Not that there’s anything wrong with that.)

class TaxFeeRulesImpl extends TaxFeeRules {
override def forTrade(trade: Trade): List[TaxFee] = {
(forHKG orElse
forSGP orElse
forAll)(trade.market)
}
val forHKG: PartialFunction[Market, List[TaxFee]] = {
case HKG =>
// in real life these can come from a database
List(TradeTax, Commission, Surcharge)
}
val forSGP: PartialFunction[Market, List[TaxFee]] = {
case SGP =>
List(TradeTax, Commission, Surcharge, VAT)
}
val forAll: PartialFunction[Market, List[TaxFee]] = {
case _ => List(TradeTax, Commission)
}
//..
}
forTrade clearly expresses the business rule, which reads almost as expressive as the English version ..PartialFunction s can be chained together to give the above model an expressive yet succinct syntax.by Debasish (ghosh.debasish@gmail.com) at February 22, 2010 05:29 AM