Contributing Scala “When to use Currying” in StackOverflow Documentation

A week or so ago I’ve contributed in StackOverflow Documentation an entry about Currying under the Scala Language tag. I’ve repeated the same exercise for Java Currying Documentation. This is how it goes:

Currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument.

This is normally useful when for example:

  1. different arguments of a function are calculated at different times. (Example 1)
  2. different arguments of a function are calculated by different tiers of the application. (Example 2)

Example 1

Let’s assume that the total yearly income is a function composed by the income and a bonus:

val totalYearlyIncome😦Int,Int) => Int =  (income, bonus) => income + bonus

The curried version of the above 2-arity function is:

val totalYearlyIncomeCurried: Int => Int => Int = totalYearlyIncome.curried

Note in the above definition that the type can be also viewed/written as:

Int => (Int => Int)

Let’s assume that the yearly income portion is known in advance:

val partialTotalYearlyIncome: Int => Int = totalYearlyIncomeCurried(10000)

And at some point down the line the bonus is known:

partialTotalYearlyIncome(100)

Example 2

Let’s assume that the car manufacturing involves the application of car wheels and car body:

val carManufacturing😦String,String) => String = (wheels, body) => wheels + body

These parts are applied by different factories:

class CarWheelsFactory {
  def applyCarWheels(carManufacturing😦String,String) => String): String => String =
          carManufacturing.curried("applied wheels..")
}
    
class CarBodyFactory {
  def applyCarBody(partialCarWithWheels: String => String): String = partialCarWithWheels("applied car body..")
}

Notice that the CarWheelsFactory above curries the car manufacturing function and only applies the wheels.

The car manufacturing process then will take the below form:

val carWheelsFactory = new CarWheelsFactory()
val carBodyFactory   = new CarBodyFactory()

val carManufacturing😦String,String) => String = (wheels, body) => wheels + body
  
val partialCarWheelsApplied: String => String  = carWheelsFactory.applyCarWheels(carManufacturing)
val carCompleted = carBodyFactory.applyCarBody(partialCarWheelsApplied)

Contributing Java “Currying” in StackOverflow Documentation

A week or so ago I’ve contributed in the StackOverflow Documentation an entry about Currying  which until now it’s mostly intact and only cosmetic changes have been made to the original. This is how it goes:

Currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument.

This can be useful when:

  1. Different arguments of a function are calculated at different times. (see Example 1)
  2. Different arguments of a function are calculated by different tiers of the application. (see Example 2)

This generic utility applies currying on a 2-argument function:

class FunctionUtils {

    public static <A,B,C> Function<A,Function<B,C>> curry(BiFunction<A, B, C> f) {
        return a -> b -> f.apply(a,b);
    }

}

The above returned curried lambda expression can also be viewed/written written as:

a -> ( b -> f.apply(a,b) );

Example 1

Let’s assume that the total yearly income is a function composed by the income and a bonus:

BiFunction<Integer,Integer,Integer> totalYearlyIncome = (income,bonus) -> income + bonus;

Let’s assume that the yearly income portion is known in advance:

Function<Integer,Integer> partialTotalYearlyIncome = FunctionUtils.curry(totalYearlyIncome).apply(10000);

And at some point down the line the bonus is known:

System.out.println(partialTotalYearlyIncome.apply(100));

Example 2

Let’s assume that the car manufacturing involves the application of car wheels and car body:

BiFunction<String,String,String> carManufacturing = (wheels,body) -> wheels.concat(body);

These parts are applied by different factories:

class CarWheelsFactory {
    public Function<String,String> applyCarWheels(BiFunction<String,String,String> carManufacturing) {
        return FunctionUtils.curry(carManufacturing).apply("applied wheels..");
    }
}

class CarBodyFactory {
    public String applyCarBody(Function<String,String> partialCarWithWheels) {
        return partialCarWithWheels.apply("applied car body..");
    }
}

Notice that the CarWheelsFactory above curries the car manufacturing function and only applies the wheels. The car manufacturing process then will take the below form:

CarWheelsFactory carWheelsFactory = new CarWheelsFactory();
CarBodyFactory   carBodyFactory   = new CarBodyFactory();

BiFunction<String,String,String> carManufacturing = (wheels,body) -> wheels.concat(body);

Function<String,String> partialCarWheelsApplied = carWheelsFactory.applyCarWheels(carManufacturing);
String carCompleted = carBodyFactory.applyCarBody(partialCarWheelsApplied);

Running Clojure via TextMate 2

TextMate 2 exists only on Mac OS X, therefore I’m assuming usage of Homebrew

1. Homebrew installation of Leiningen

$ brew install leiningen

2. Installation of Leiningen lein-exec plugin via adding to ~/.lein/profiles.clj:

{:user {:plugins [[lein-exec "0.3.5"]]}}

3. Manual installation of the (old) TextMate Clojure Bundle. TextMate 2 Bundles are living now under this directory and not as described in the Github repo:

cd ~/Library/Application\ Support/TextMate/Managed/Bundles/

4. Within TextMate 2 > Edit Bundles > Clojure > Menu Actions > Rename and edit the ‘Cake Start’ to ‘Run’ with the following scriptlet:

#!/bin/bash
[[ -f "${TM_SUPPORT_PATH}/lib/bash_init.sh" ]] && . "${TM_SUPPORT_PATH}/lib/bash_init.sh"
if [ -e “${TM_FILEPATH}” ]; then
“/usr/local/bin/lein” “exec” “${TM_FILEPATH}”
exit_show_tool_tip
else
puts “File not found or not saved. Please save first”
fi

DSL example in Scala

Here’s a DSL example in Scala that will allow us to express amounts in the context of currencies taking into account the FX rates too.

By the end of it we’ll be able to write the following:

'USD(100) + 'EUR(200) in 'EUR

Here’s the code for it:

object ScalaForexRatesDSL {

  implicit class ccy2money(ccy :Symbol) {
    def apply(amount: BigDecimal) = Money(amount, ccy)
  }
}

case class FromToCcy(ccyFrom: Symbol, ccyTo: Symbol)

case class Money(amount:BigDecimal, ccy:Symbol) {

  def + (other: Money)(implicit rates: Map[FromToCcy, BigDecimal]): Money =
    if(ccy == other.ccy) Money(amount + other.amount, ccy) else {
      val convertedOther = convertedOtherMoney(other)
      Money(amount + convertedOther.amount, ccy)
    }

  def - (other: Money)(implicit rates: Map[FromToCcy, BigDecimal]): Money =
    if(ccy == other.ccy) Money(amount - other.amount, ccy) else {
      val convertedOther = convertedOtherMoney(other)
      Money(amount - convertedOther.amount, ccy)
    }

  def * (other: Money)(implicit rates: Map[FromToCcy, BigDecimal]): Money =
    if(ccy == other.ccy) Money(amount * other.amount, ccy) else {
      val convertedOther = convertedOtherMoney(other)
      Money(amount * convertedOther.amount, ccy)
    }

  def / (other: Money)(implicit rates: Map[FromToCcy, BigDecimal]): Money =
    if(ccy == other.ccy) Money(amount / other.amount, ccy) else {
      val convertedOther = convertedOtherMoney(other)
      Money(amount / convertedOther.amount, ccy)
    }

  private def convertedOtherMoney(other: Money)(implicit rates: Map[FromToCcy, BigDecimal]): Money = {
    val rate = rates.get(FromToCcy(other.ccy, ccy)).getOrElse(1 / rates.get(FromToCcy(ccy, other.ccy)).get)
    Money(other.amount * rate, ccy)
  }

  def in(ccy: Symbol)(implicit rates: Map[FromToCcy, BigDecimal]): Money =
    if (this.ccy == ccy) this else {
      val rate = rates.get(FromToCcy(this.ccy, ccy)).getOrElse(1 / rates.get(FromToCcy(ccy, this.ccy)).get)
      Money(amount * rate, ccy)
    }

  override def toString = amount + " " + ccy.name
}


object Main extends App {

  import ScalaForexRatesDSL._

  implicit val rates = Map((FromToCcy('EUR, 'USD) -> BigDecimal(1.13)))

  print( 'USD(100) + 'EUR(200) in 'EUR )

}

Spring Boot – Testing

Spring Boot dependency for Testing is bringing exactly what I would have wished for (I hope they would include in the future the upcoming AssertJ).

The dependency looks like this:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

and brings in the classpath the usual Testing suspects: JUnit4, Mockito and Hamcrest.

Screen Shot 2015-07-12 at 21.18.17

Spring Boot – Logging

As is the case with any new framework (or major addition to an existing and well known framework) the best way to approach it, work with it and learn it is not to dive head first but rather take baby steps in areas that feel more accessible and can link with ideas/processes/steps you are already following.

Spring Boot is sporting several starter recipes that can speedup your configuration and can be consumed separately to each other.

Let’s first talk about logging.

The best practise is to code against SLF4J, provide a desired implementation (preferably Logback), and include in the classpath SLF4J bridges for JUL, JCL and Log4J.

The process is described here by the person/team that authored SLF4J, Log4J, Log4j2, Logback and all the 3 SLF4J bridges namely for JUL, JCL, and Log4J.

The design we described and we are aiming at is also well depicted in the link above and is provided here for quick reference:

Screen Shot 2015-07-12 at 21.03.18

Let’s now get back to Spring Boot.

The Spring Boot dependency module is the following:


		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</dependency>

That is actually doing all we want and described above effortlessly leaving our classpath changed by this much:

Screen Shot 2015-07-12 at 21.09.39

Scala Option Advanced example

I’ve been tinkering with mime types in a toy Scalatra file server so while maintain a file with all known mime types a common task is to figure out the extension of a given file name.

With a bit out-of-the-box thinking on capturing the extension but without using Options therefore open to failures:

def findExtension(s:String)=s.reverse.takeWhile(_!='.').reverse

Here’s how it looks while wrapping the string in the Option monad and performing type-safe operations on it before returning a Some or None of the extension:

scala> def findExtension(s:String)=
 Option(s) //wrap into Option
 .filter(_.exists(_=='.'))  //ignore files without a dot
 .map(_.reverse)  //out-of-the-box thinking
 .map(_.takeWhile(_!='.'))  //maybe could be done with some non-greedy advanced regex too
 .filter(_.trim.nonEmpty)  //take "" empty strings as None
 .map(_.reverse)  //reverse back
findExtension: (s: String)Option[String]

scala> findExtension("hi")
res128: Option[String] = None

scala> findExtension("h.io")
res129: Option[String] = Some(io)

scala> findExtension("www.github.io")
res130: Option[String] = Some(io)

Scala For-Comprehension Advanced usage

Let’s say we want to find all three-pair additions that equate to 10 (order is irrelevant so we don’t want dups). What we would normally do in imperative Java would be 3 nested for loops with indexes say i, j and k where i ranges from 1 till 10, j starts from i+1 and k starts from j+1. The body of the for loop would be the if predicate case. We would also need a variable to store the results.

Instead in Scala:


val l = List(1,2,3,4,5,6,7,8,9,10)

for {
   (a,i) <- l.zipWithIndex
   (b,j) <- l.zipWithIndex.drop(i+1)
      c  <- l.drop(j+1)
   if 10 == a + b + c
} println(s"$a $b $c") 

We can also use for comprehension with yield as a returned assignable result rather than println

Stopwatch implementation in Scala

Timing method operations can be a labouring task littering the method body with the timing variables (sometimes short-lived as in debug mode). Thankfully we can treat the timing activity as a pass-by-name method argument of our newly defined timing operation:

def timed [T] (f: => T): T = {
 val startTime = System.currentTimeMillis()
 try f finally println(s"Function completed in: ${System.currentTimeMillis() - startTime} ms" )
}

Scala call-by-name

The arguement notation : => A denotes passing the argument in call-by-name manner not the traditional call-by-value fashion. That essentially means:

  • If the parameter is never used, it is never evaluated
  • If the parameter is used multiple times, it is getting evaluated each and every time in the by-name invocation

Traditionally call-by-value invocation would be evalutated just once and the calculated value would be just pushed in the method stack:

def myprint(date: java.util.Date):Unit = for(i->1 to 5) println(date)

scala> myprint( {Thread.sleep(1000); new java.util.Date()} )
Sun Apr 27 10:10:37 GMT 2014
Sun Apr 27 10:10:37 GMT 2014
Sun Apr 27 10:10:37 GMT 2014
Sun Apr 27 10:10:37 GMT 2014
Sun Apr 27 10:10:37 GMT 2014

whereas call-by-name would be evaluated each and every time anew:

def myprint(date :=> java.util.Date):Unit = for(i->1 to 5) println(date)

scala&gt; myprint( {Thread.sleep(1000); new java.util.Date()} )
Sun Apr 27 10:12:46 GMT 2014
Sun Apr 27 10:12:47 GMT 2014
Sun Apr 27 10:12:48 GMT 2014
Sun Apr 27 10:12:49 GMT 2014
Sun Apr 27 10:12:50 GMT 2014