Software surgery, programming, architecture, process, development, design, and more...
4/1/09
Quote of the month
2/8/09
Flavors of Curry: Scala vs Haskell
Scala is a nice language to explore functional programming, and for me it was easy to use it as a “stepping stone” and jump to Haskell with all the purity and laziness (I think is because I'm the kind of guy that enter slowly in the cold water...). I'm using Haskell to learn the theory and tools of functional programming (in a language that forces you to), so I can use them in Scala.
To that end, I'm going through “Learn You a Haskell for Great Good!” (I seem to have a fondness for technical books with silly images). Usually I'll try to do the same exercises in Scala to compare.
I was going through the chapter about higher order functions and currying. What are curried functions? You can find a very good explanation in wikipedia (of course!). Basically is the transformation of a function with multiple parameters into another function with only one parameter that returns a function of the remaining parameters. With that, your language can care only about functions with only one parameter and still be equally powerful. The advantage is if you call a function with less parameters, you get a partially applied function.
One of the examples on the “Learn you...” is a “flip” function: a function that exchanges the first and second parameter of a given function. In Haskell is as easy as:
flip1 f x y = f y xThat's all! Hindley-Milner type inference ensures the type safety:
flip1 :: (t1 -> t -> t2) -> t -> t1 -> t2As an example:
f x y =x/y
f 1 2
0.5
g= flip1 f
g 1 2
2.0
BTW, there's something odd:
Prelude> let flip1 f x y = f y x
Prelude> :t flip1
flip1 :: (t1 -> t -> t2) -> t -> t1 -> t2
Prelude> let f x y =x/y
Prelude> :t f
f :: (Fractional a) => a -> a -> a
Prelude> let g=flip f
Prelude> :t g
g :: Double -> Double -> Double
Prelude> :t flip1 f
flip1 f :: (Fractional t1) => t1 -> t1 -> t1
The type of flip1 f is (Fractional t1) => t1 -> t1 -> t1, meaning that t1 is restricted to be of Fractional typeclass, but if I bind g to flip f, now the type is Double... that's not what one would expect! (Any Haskell expert can tell me what's happening?)
As usual, I'll tried to do the same in Scala to see how far it can goes.
The main difference is of course, type inference: in Scala you need to declare the function types. The other major difference is Haskell every function is curried by default, in Scala you need to explicitly curry the function by separating each parameter between parentheses.
In Scala, our (curried) f function will be:
def f(x:Int)(y:Int)=x/y
f: (Int)(Int)Int
The flip function in Scala would be:
def flip1[A,B,C]( f:A=>B=>C)(x:B)(y:A) =f(y)(x)
flip1: [A,B,C]((A) => (B) => C)(B)(A)C
Is clearly more verbose than the Haskell version, but equally powerful:
def g = flip1 (f) _
g: (Int) => (Int) => Int
The underscore is needed to get the partially applied function and the f must be in parentheses (again, all curried parameters must have their own parentheses).
Conclusion? Nothing. Haskell and Scala are obviously different, but they share some common ground... just wanted to show it :)
12/18/08
Playing with Scala 5 ½: More variations
As James pointed out, the implicit conversion creates a new object every time we convert the Node to Ordered[Node], and although the JVM and the GC can deal pretty well with that kind of scenario, it will be better if we can avoid the creation of the object (BTW, the fact that Scala can leverage years of work on JIT optimizations is something that shouldn't be taken lightly... I still want tail call optimization, though)
We need to add the Ordered trait for Node somewhere in the hierarchy. The reasonable place is when we add the Weight trait (once we have weight we can compare the nodes):
class DfsNode extends NodeImpl with Weight with Ordered[DfsNode]{
...
def compare(y: Node): Int = this.weight.compare(y.weight)
}
Now we can compare the nodes by their weight: “lighter” nodes are before “heavier” nodes, but the comparation is not what we need for the priority queue, we need to reverse the the ordering.
The most immediate way is just reverse DfsNode's comparation function:
def compare(y: Node): Int = -this.weight.compare(y.weight)
but this has the undesirable effect of reversing all the node comparations, and most of the time I'll bet we want to have the lighter nodes before the heavier ones, the reverse is counter-intuitive (and the potential source of nightmares). The solution? Let's create our particular flavor of DfsNode with the comparation reversed to use it in the PriorityQeue:
class PQNode extends DfsNode {
override def compare(y: Node): Int = -super.compare(y)
}
And we just need to change our newNode method to return PQNodes instead of DfsNodes:
protected def newNode: Node = new PQNode
For extra points on modularization, we can extract those changes and the code related to the algorithm in a subclass of DfsGraph.
Here is the complete code:
package dfs2;
abstract class Graph {
type Edge
type Node <: NodeIntf
abstract class NodeIntf {
def connectWith(node: Node): Edge
}
def nodes: Set[Node]
def edges: Set[Edge]
def addNode: Node
}
abstract class DirectedGraph extends Graph {
type Edge <: EdgeImpl
class EdgeImpl(origin: Node, dest: Node) {
def from = origin
def to = dest
}
class NodeImpl extends NodeIntf {
self: Node =>
def connectWith(node: Node): Edge = {
val edge = newEdge(this, node)
edges = edges + edge
edge
}
}
protected def newNode: Node
protected def newEdge(from: Node, to: Node): Edge
var nodes: Set[Node] =Set()
var edges: Set[Edge] =Set()
def addNode: Node = {
val node = newNode
nodes = nodes + node
node
}
}
trait Weight {
var weight= Float.PositiveInfinity
}
import scala.collection.mutable.PriorityQueue;
class DfsGraph extends DirectedGraph {
class DfsNode extends NodeImpl with Weight with Ordered[DfsNode]{
var previous: DfsNode = _
var label:String = _
var nodeEdges: Set[Edge] = Set()
override def connectWith(node: Node): Edge = {
val newEdge=super.connectWith(node)
nodeEdges = nodeEdges + newEdge
newEdge
}
def -->(n2:Node):DfsEdge =connectWith(n2)
override def toString()= label+ " w:"+weight
def compare(y: Node): Int = this.weight.compare(y.weight)
}
class DfsEdge(origin:Node, dest:Node) extends EdgeImpl(origin, dest) with Weight {
override def toString()= from.label+"-->"+to.label+" w:"+weight
}
def addNewNode(l:String):Node={
val newNode=super.addNode
newNode.label=l
newNode
}
type Node= DfsNode
type Edge= DfsEdge
protected def newEdge(from: Node, to: Node): Edge = new DfsEdge(from,to)
protected def newNode: Node = new DfsNode
}
class DijkstraSPGraph extends DfsGraph {
class PQNode extends DfsNode {
override def compare(y: Node): Int = -super.compare(y)
}
override protected def newNode: Node = new PQNode
def shortestPath(start: DfsNode, end: DfsNode) = {
val unvisited=new PriorityQueue[Node]()
unvisited++=(nodes)
start.weight=0
while (!unvisited.isEmpty) {
val vertx=unvisited.dequeue
for (v <- vertx.nodeEdges if canImprove(v)){
unvisited+improveDistance(v)
}
}
}
def canImprove(a:Edge)=(a.from.weight+a.weight< a.to.weight)
def improveDistance(a:Edge) ={
val v=a.to
v.weight=a.from.weight+a.weight
v.previous=a.from
v
}
def pathToStart(end:DfsNode):List[DfsNode] = {
if (end == null)
Nil
else
end :: pathToStart(end.previous)
}
}
object Example extends Application {
val graph = new DijkstraSPGraph
val n1=graph addNewNode "start"
val n2=graph addNewNode "n2"
val n3=graph addNewNode "n3"
val n4=graph addNewNode "n4"
val n5=graph addNewNode "n5"
val n6=graph addNewNode "end"
graph addNewNode "alone"
n1-->n2 weight=2
n1-->n3 weight=1
n2-->n4 weight=1
n3-->n4 weight=3
n2-->n5 weight=1
n4-->n6 weight=1
n5-->n6 weight=3
n1-->n6 weight=7
n1-->n4 weight=10
graph.shortestPath(n1,n6)
println("Path")
graph.pathToStart(n6).reverse.map(println(_))
}
12/14/08
Playing with Scala 5: improving code, use of views and comprehensions
The first change is replace the set with Scala's priority queue:
val unvisited=new PriorityQueue[Node]()
But as it is, it will not compile: the priority queue's signature is
class PriorityQueue[A](implicit view$1 : (A) => Ordered[A]) extends ResizableArray[A] with CloneableCollection
You need to provide an implicit conversion from the parameter type A to the type Ordered[A]. But nothing to worry about: is as easy as
implicit def node2ordered(n: Node): Ordered[Node] = new Ordered[Node] {
//reverse the comparation so highest priority = lower cost
def compare(y: Node): Int = -(n.weight.compare(y.weight))
}
Look at the improveDistance function, it does two things: filters the nodes and updates the distance if we can improve it. I think is better if we split into two different functions, separating the filtering from the updating, so instead of:
def improveDistance(a:Edge) ={
if (a.from.weight+a.weight< a.to.weight) {
a.to.weight=a.from.weight+a.weight
a.to.previous=a.from
}
}
we get:
def canImprove(a:Edge)=(a.from.weight+a.weight< a.to.weight)
and
def improveDistance(a:Edge) ={
a.to.weight=a.from.weight+a.weight
a.to.previous=a.from
a.to
}
Then, instead of a function map over the nodeEdges, we have to filter and then map:
vertx.nodeEdges.map(improveDistance(_))
is replaced by
vertx.nodeEdges.filter(canImprove(_))).map(improveDistance(_)
that gives a better picture of the steps involved.
As we need to add the updated nodes to the priority queue so they can “float” to the top, the line would look like:
unvisited++ (vertx.nodeEdges.filter(canImprove(_))).map(improveDistance(_))
But I don't really think the explicit use of map and filter helps readability.
Enter Scala's for comprehensions: we can replace the map/filter with a comprehension:
for (v <- vertx.nodeEdges if canImprove(v)){
unvisited+improveDistance(v)
}
Nothing fantastic, but an improvement, isn't it?
For future posts, I'm planning on generalizing the algorithm into a A* pathfinding with different heuristic functions... stay tuned!
10/22/08
Simple Java tricks to protect your web application against SQL injection
Sometimes, you have to work with plain JDBC (or ODBC). Here is a couple of tricks that help:
- First and foremost, avoid concatenating strings for SQL queries. Use prepared statements unless is not possible (i.e. cases when you have undefined number of parameters)
- Leverage the language type system: If you're passing a number, use Integer instead of String... any invalid character will fail the conversion and will not reach the DB.
- If there's no option but concatenate strings, make sure the database comment quotes are escaped (for example, in DB2 you have to replace the single quote character with 2 single quote characters: instead of "SELECT * FROM users WHERE name='"+param+"'" use "SELECT * FROM users WHERE name='"+param.replaceAll("'","''")+"'"
Note: by no means this is a comprehensive list. Application security is very hard, check your database documentation...
9/24/08
Java: The programming tool of choice for discriminating hackers
while(tongue in cheek){
take(this);
(lisp (snobs all))
fuctional_programing = Maybe[zealots]
ruby('fanboys')
}
Another proof of what matters is not the tool, is how you use it...
8/25/08
State machines using "Fluent interfaces/ DSL" in Java
In my previous project, I started with a simple design using a transition matrix. I must confess it didn't work well. It was hard to explain and it grew more complex as new requirements were added. I though it would be simpler if I didn't use any "fancy OO stuff" and advanced idioms. I've should know better!
This time I wanted to try something different, and based in my previous experiments with internal DSLs with Scala and my (very limited) knowledge of the patters to achieve that in java, I just went ahead and tried to come up with something useful and understandable. This time seems to be working: although it has some "magic" behind curtains is only in the creation and is very easy to add or modify the configuration class for new or updated states and events. Other members of my project were able to add and remove states and transitions with only a brief explanation.
The basic classes are pretty simple: State and Event.
package statemachine;
public class Event {
final private String label;
public Event(String newLabel){
label=newLabel;
}
/**
* @return Returns the label.
*/
public String getLabel() {
return label;
}
public String toString(){
return label;
}
}
package statemachine;
import java.util.HashMap;
import java.util.Map;
public class State {
private final String label;
private final Map<Event,Transition> transitions= new HashMap<Event,Transition>();
//no public access to the constructor, must be in the same package
State(String newLabel){
this.label=newLabel;
}
void addTransition(Transition t){
transitions.put(t.getEvent(),t);
}
public State doEvent(Event e){
return (transitions.get(e)).getDestination();
}
/**
* @return Returns the label.
*/
public String getLabel() {
return label;
}
/**
* @return Returns the transitions.
*/
public Map<Event,Transition> getTransitions() {
return transitions;
}
}
You send a event to a sate and it returns the next state:
State newState=state.doEvent(event);
The State class holds a map of [event->state] (with the Transition class in the middle, for added effect :) )
As an extra safety measure, the State constructor and the addTransition method is accessible only to the package (well, unless you subclass it)
The "fluency" is provided by the Transition class (the useful methods return this to allow method chaining), so you can write:
new Transition(event).from(origin).to(destination)
package statemachine;
class Transition {
private State origin,destination;
private Event event;
public Transition(Event e){
event=e;
}
public Transition from(State orig){
origin=orig;
origin.addTransition(this);
return this;
}
public Transition to(State dest){
destination=dest;
return this;
}
/**
* @return Returns the destination.
*/
public State getDestination() {
return destination;
}
/**
* @return Returns the event.
*/
public Event getEvent() {
return event;
}
/**
* @return Returns the origin.
*/
public State getOrigin() {
return origin;
}
}
How this will look? Suppose you have a pretty simple FSM:

Using the previous pseudoDSL/Fluent interface will look like:
package statemachine;
public class FSMDef {
public final static State SUBMITTED=new State("Submitted");
public final static State OPEN= new State("Open");
public final static State CANCELLED= new State("Cancelled");
public final static State CLOSED= new State("Closed");
//Events
static class Events {
public final static Event OPEN = new Event("Open");
public final static Event CLOSE = new Event("Close");
public final static Event REOPEN = new Event("Re-Open");
public final static Event CANCEL = new Event("Cancel");
}
static {
new Transition(Events.OPEN).from(SUBMITTED).to(OPEN);
new Transition(Events.CLOSE).from(OPEN).to(CLOSED);
new Transition(Events.REOPEN).from(CLOSED).to(OPEN);
new Transition(Events.CANCEL).from(OPEN).to(CANCELLED);
}
}
Doesn't seems too complex, right?
I'm just starting with this, and probably barely skim the surface (sure it has some drawbacks), but so far it worked :)
[EDIT: Fixed the generics declarations that were eaten by the HTML format. BTW, if anybody knows a good code formatter for blog posts, let me know ]