Pivotal Labs

Main menu

Skip to primary content
Skip to secondary content
  • About
  • Case Studies
  • Team
    • Executives
    • Locations
      • San Francisco (HQ)
      • Boston
      • Boulder
      • Denver
      • London
      • Los Angeles
      • New York
  • Community
    • Blogs
    • Tech Talks
    • Events
  • Careers
    • Lifestyle
    • Principles & Practices
    • Benefits
    • FAQ
    • Apply
  • Contact
    • Press Room
    • Press Releases
    • In The News
    • Press Kit
  • All
  • Labs
  • Standup
  • Tracker
Robbie Clutton

Failed attempt at trying to use refinements

Robbie Clutton
Monday, April 8, 2013

I was pretty interested in refinements in Ruby 2.0, and after listening to the latest Ruby Rouges podcast where some serious doubts were raised about the viability of refinements I thought I’d build a little example of how I was thinking I could use it.

I failed first time out and I tried copying and pasting examples without success. After some time poking around I found a blog post about why this wasn’t working. Ultimately, refinements are sort of left in the language, but not fully supported and are marked as experimental.

Here’s what I wanted to achieve. Coming from Scala in my previous job, I thought I could use refinements as a proxy for implicit conversions. Here I refine the Fixnum class to allow it to respond to a to_currency message. When called it converts the Fixnum instance to a Currency instance.

class Currency
  attr_reader :units

  def initialize units
    @units = units
  end
end

module CurrencyExtensions
  refine Fixnum do
    def to_currency
      Currency.new(self)
    end
  end
end

class App
  using CurrencyExtensions

  def initialize
    puts 3.to_currency
  end
end

App.new

Why is this interesting to me? Well, I think being able to write 3.to_currency can result in nicer to read code than the alternative Currency.new(3). Small difference perhaps.

There is a way to get this to work by having the using keyword in the global context, but it doesn’t deliver the full impact I was hoping for.

class Currency
  attr_reader :units

  def initialize units
    @units = units
  end
end

module CurrencyExtensions
  refine Fixnum do
    def to_currency
      Currency.new(self)
    end
  end
end

using CurrencyExtensions
puts 3.to_currency

I’ve got other ideas to build upon this if it ever makes it into the full specification. I’ll keep watching for now.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
John Barker

Why you should care about functional programming.

John Barker
Wednesday, January 30, 2013

I’ve been experimenting with functional programming (FP) languages for a little while now and their acceptance is generally increasing amongst the wider developer community. This is the first post in a series of articles I hope to do that explore FP, what it is and what we could learn from this trend.

Why now?

Functional programming languages are by no means new. LISP often thought of as one of the first programming languages was developed in 1958. IPL a sort of assembler like symbolic language appeared in 1954. The foundations of FP are embedded in mathematical constructs much older than the concept of an electronic computer.

But for all intents and purposes they sort of disappeared into obscurity, replaced by procedural languages like C or Object Orientated (OO) like C++ or Java. Partially because they were impractical – some of the constructs used by FP languages performed worse than their imperative counterparts. In a time when CPU power was scarce, this was not an option.

A different age

Thanks to Moore’s law this has changed somewhat. Computers now are certainly more powerful then they were when the first LISP interpreter appeared. But the ever scaling MHZ peak has slowed. New CPUs come with more cores, not more cycles. To take advantage of these improvements we need to look to parallelization and FP languages are inherently suited to this kind of work.

I am not alone in recognizing this. IBM released this article recognizing the rising trend. ThoughtWorks has identified Scala and Clojure in its technology radar and recognizes momentum building behind several FP languages: http://www.drdobbs.com/mobile/thoughtworks-eyes-seismic-shift-in-progr/240009675. Spend any time on Hacker News and you’ll regularly see links on the topic.

I feel like FP is an idea whose time has come and I’m very excited by the new languages, ideas and technologies that are appearing. Hopefully Pivotal Labs will someday join me on this journey.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Robbie Clutton

Scala Options

Robbie Clutton
Thursday, February 23, 2012

I tried to explain Options in Scala in a lightening talk this week and I don’t think I did a particular good job at this. I started by talking about how you might use Options instead of doing null checks in a first step towards a more idiomatic way of using Scala, but perhaps I should have skipped that and gone straight to the interesting parts. So while my presentation is available with those comments, here I will skip the first half of that and get to it.

An Option represents an optional value, it either contains a value, or it does not. In Scala the terms used are that an option has Some of X, or None. While this does give you some nice wrap around doing Null checks, it doesn’t buy you much more than that until you consider that an Option can be thought about as a sequence of zero or one elements, and that you can use functions on an Option that you would do on a list. This gives you access to map, filter, flat map and all the others.

This in turn opens up the world of transformations and list comprehensions. Now we’re going into idiomatic Scala. One of the most used elements in Scala that I’ve seen is taking one object and transforming that into another. When transformations are done a few at a time, you can quickly eliminate a lot of plumbing code through chaining calls to get to what you need. You can do this safely using Options as each step in the chain returns an Option, and the first step in the chain to return a None will evaluate the whole expression as None.

This example has an option of a person, transforms that into an option of department and then into an option of the department name as a string. If at any time the object is None, the whole statement will return None. If it gets through to the department name, it will return a Some of String (Some[String]). The underscore in the example is the value within the Option after the map has been applied. This can be assigned to a locally scoped variable too, but for conciseness, I’m using the underscore.

val personOption = Some(person)

val departmentName1 = personOption.flatMap { person => person.department } map { department => department.name }

val departmentName2 = personOption flatMap { _ department } map { _ name }

Options have functions that allow you to retrieve the value, retrieve the value with a given default if the value is None, or check to see if the object is defined. To get the name of the department, we can do:

val deptName = departmentName1 getOrElse (“No department”)

That’s cool, but we can go one further with list comprehension. This is where we turn a list into another list. Remember earlier we said an Option can be considered an sequence of zero or more elements, so we can apply list comprehension to an option and return an option. Each line here will assign from right to left, and if at any step something on the right is None, the expression will be None. We can also apply conditions into the comprehension, so that if the name of the department is engineering the whole expression returns None.

val departmentName3 = for {
    person <- personOption
    department <- person.department
} yield department.name

Both of these method can be applied to lists as well as options, so that if personOption was actually a list of people, the result would be a list of department names. Here we apply the same code to a list to get all the non-engineering department names.

val person2 = Person(Some(Department("Design")))

val people = List(person, person2)

val nonEngineeringDepartments = for {
    person <- people
    department <- person.department if department.name != "Engineering"
} yield department.name

This train of thought started when I wanted to do something in Ruby that I knew how to do in Scala and it turned into me trying to explain some of these concepts in Scala. I’m still fairly new to Ruby, and I’m not saying ‘I wish I could do this in Ruby’, more ‘I wish I knew if I could do this in Ruby’.

More code is available in this Gist: https://gist.github.com/059d04ccc03d86081f84

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Glenn Jahnke

Polyglot Factorial

Glenn Jahnke
Tuesday, November 15, 2011

Someone on Hacker News mentioned the number of orderings of a deck of cards. I took up the challenge in some of my favorite and not so favorite languages, I’ll let you guess :).

Ruby

ruby-1.9.2-p180> (1..52).inject{|a,b|a*b}
=>
80658175170943878571660636856403766975289505440883277824000000000000

Scala

scala> BigInt(1).to(BigInt(52)).toList.foldLeft(BigInt(1))((a,b) => a*b)
res23: scala.math.BigInt =>
80658175170943878571660636856403766975289505440883277824000000000000

Haskell

Prelude> foldl1 (x -> y -> x*y) [1..52]
80658175170943878571660636856403766975289505440883277824000000000000

CoffeeScript

coffee> [1..52].reduce (a,b) -> a*b

8.065817517094388e+67

Java

Non-existent REPL>
import java.math.*;
public class Factorial {
public static void main(String[] args) {
BigInteger result = BigInteger.ONE;
BigInteger fiftyTwo = new BigInteger(”52″);
for(BigInteger i = BigInteger.ONE; i.compareTo(fiftyTwo) <= 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(i);
}
System.out.println(result);
}
}

$ java Factorial
80658175170943878571660636856403766975289505440883277824000000000000

** I could have used the product function in most of those examples, but I wanted to play with foldL ;)

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Glenn Jahnke

Adventures in TDDing Scala Actors with Scalatest

Glenn Jahnke
Saturday, February 27, 2010

Recently, Martin Odersky and David Pollak visited Pivotal Labs to show off Scala and its Lift web framework. I have an ongoing interest in concurrent programming and this resparked my interest in Scala and its Actors, a library that leverages the Erlang style concurrency model but with a (relatively) more familiar JVM language. I began spiking on a project with Actors some time ago but hit several issues that made me really want to test-drive the project to both drive out better design, and hopefully eliminate some of these bugs in a more productive manner.

After some effort reading documentation about both ScalaTest and Scala’s Actors, and wrangling with the compiler for a while, here is where I am so far.

The test for a very simple Square class that accepts three messages, then returns the maximum.

package test

import org.scalatest._
import matchers.MustMatchers
import main.Square

class SquareSpec extends Spec with MustMatchers {
  describe("Square") {
    it("returns the max of 3 messages received") {
      val timeout = 500
      val square = new Square
      square ! 1
      square ! 3
      (square !? (timeout, 2)).get must equal(3)
    }
  }
}

Here is the implementation.

package main

import scala.actors.Actor
import scala.actors.Actor._

class Square extends Actor {
  var numMessagesReceived = 0
  var maxMessageReceived = Integer.MIN_VALUE
  this.start
  def act() {
    loop {
      react {
        case msg : Int => replyWhenNecessary(msg)
      }
    }
  }

  def replyWhenNecessary(msg : Int) {
    println(msg)
    maxMessageReceived = if(maxMessageReceived > msg) {maxMessageReceived} else {msg}
    numMessagesReceived += 1
    if(numMessagesReceived == 3) {
      reply(maxMessageReceived)
      exit
    }
  }
}

Things I learned:

Scala

  • Scala’s classes don’t call out the main constructor, you just dump the class variables in parentheses after the class name and constructor code inside the body of the class

Actors

  • You can use the method!?(timeout, message) in place of !(message) to synchronously, and with a timeout, get a return message from the actor. The actor must reply though. The timeout is great for testing, often you’ll have an actor in an infinite loop and your test won’t complete instead of failing nicely.

ScalaTest

  • ScalaTest has several flavors of test, but the one that most Rubyists will appreciate is having your test class extend Spec as it is most similar to RSpec.

General

  • IntelliJ Community Edition with the Scala plugin is pretty awesome.

Hopefully I’ll have more later as I continue my effort to learn how to test concurrent programming.

  • 0 Shares
  • Share on Facebook
  • Share on Twitter

Topics

  • agile (780)
  • rails (113)
  • testing (88)
  • ruby (83)
  • ruby on rails (70)
  • jobs (62)
  • javascript (55)
  • techtalk (44)
  • rspec (38)
  • ironblogger (32)
  • productivity (30)
  • activerecord (29)
  • gogaruco (29)
  • git (28)
  • nyc (27)
  • rubymine (26)
  • bloggerdome (23)
  • mobile (22)
  • process (21)
  • pivotal tracker (20)
  • cucumber (20)
  • jasmine (19)
  • design (18)
  • ios (18)
  • webos (17)
  • objective-c (17)
  • android (16)
  • palm (16)
  • "soft" ware (16)
  • fun (15)
  • tracker ecosystem (15)
  • ci (15)
  • cedar (15)
  • rails3 (14)
  • performance (14)
  • bdd (14)
  • gem (13)
  • css (13)
  • tdd (13)
  • selenium (12)
  • goruco (12)
  • bundler (12)
  • meetup (11)
  • railsconf (11)
  • nyc-standup (11)
  • capybara (10)
  • mac (10)
  • mojo (10)
  • chef (10)
  • api (10)
Subscribe to scala Feed
  • About
  • Case Studies
  • Team
  • Community
  • Careers
  • Contact
  • Labs
  • Events

Contact Us

contact@pivotallabs.com
+1 415-77-PIVOT
TwitterLinkedInFacebook

Pivotal Tracker

Tracker is the award-winning agile project management tool that enables real-time collaboration around a shared, prioritized backlog.
Visit pivotaltracker.com >