Thursday, 2 July 2009

More Partial Functions

Here I am defining a couple of PartialFunctions and using them:

def main(args :Array[String]) :Unit = {

def f1 : PartialFunction[List[String], String] = {
case "a" :: rest => "I got an A"
}
def f2 : PartialFunction[List[String], String] = {
case "a" :: "b" :: rest => "I got an A and the next letter is a B"
}
def f3 = f2 orElse f1

println( handleRequest2( "a"::"c"::"a"::"b"::Nil)(f3) )
}

def handleRequest2(req : List[String])
(exceptions : PartialFunction[List[String], String]) : String = {
if (req.isEmpty) {
""
} else if (exceptions.isDefinedAt(req)) {
exceptions(req) + "\n" + handleRequest2( req.tail )(exceptions)
} else {
"Normal handle "+req.head+" ..done" + "\n" + handleRequest2( req.tail(exceptions)
}
}


Output [is unsurprisingly]:

I got an A
Normal handle c ..done
I got an A and the next letter is a B
Normal handle b ..done

No comments:

Post a comment