Showing posts with label scala. Show all posts
Showing posts with label scala. Show all posts

Wednesday, April 10, 2013

scala yield vs map which is nicer?

currently I'm playing a bit more with scala in an attempt to leverage the power of my new pair of radeon 7970 for GPU calculations and I'm a touch unsure, which syntax I prefer and is easier to read.

example a:


scala> 1 to 10 map ( _ * 2)
res4: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)


versus example b:

scala> for (i <- 10="" 1="" 2="" i="" nbsp="" to="" yield="">
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)


They both produce the same result, but I feel the b is easier to understand from a none scala perspective. But a. Is shorter and somewhat clearer

Now if we change this to:


scala> val result  = 1 to 10 map ( _ * 2)
result: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

and

scala> val result = for (i <- 10="" 1="" 2="" i="" nbsp="" to="" yield="">
result: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

now the first version seems to make a lot more sense and the second looks unwieldy complicated.

Monday, March 11, 2013

Lift - getting access to a database

Since I recently started to play more and more with lift. I discovered that it's not always as easy as you think it is and once you find a solution it was easy indeed.

For example I want to connect to my database server, but have no desire to actually use any form of OR mapping.

So after googleing a bit and woundering how todo this. It's all rather simple.

In your Boot.scala file


def boot {
    // where to search snippet
    LiftRules.addToPackages("code")

    // Build SiteMap
    LiftRules.setSiteMap(sitemap)

    //rest based stuff

    /**
     * connection url for lift
     */
    val vendor = new StandardDBVendor("org.postgresql.Driver","jdbc:postgresql://****/****",Full("username"),Full("password")) with ProtoDBVendor{
      override def maxPoolSize = 100
      override def doNotExpandBeyond = 200
    }
    
    DB.defineConnectionManager(DefaultConnectionIdentifier, vendor)

  }

This basically defines what to connect to and a connection pool with a max of 100 connections.

To actually access this connection and todo something with it, well this is remarkable easy.


          DB.performQuery("select * from data")

Tuesday, January 29, 2013

scala + lift + json

So since I really really really dislike soap and Java, I decided to play a bit more with scala and rest based web services. Basically parse some JSON strings with scala.

Now after browsing countless articles and remembering the JSON structure, I finally found the 'lift-json' project, which simplifies my live as busy developer a bit.

How to parse JSON with scala?


package edu.ucdavis.fiehnlab.alchemy.core.communication.services.reader
import edu.ucdavis.fiehnlab.alchemy.core.process.types.LibrarySpectra
import net.liftweb.json.parse
import net.liftweb.json.DefaultFormats
/**
 * connects to the alchemy webservice and fetches all registered co
 */
class WebserviceLibraryReader {

  /**
   * internal converter class to simplify things
   */
  case class JsonCompound(name: String, inchikey: String, retentiontime: Double, theoretical: Double, massspectra: String)

  case class CompoundWapper(compound: Array[JsonCompound])

  implicit val formats = DefaultFormats

  /**
   * downloads the compounds for the given URL and returns it as a set of library spectra
   */
  def fetchCompounds(url: String): Set[LibrarySpectra] = {

    val compounds: CompoundWapper = parse("""
        
        {"compound":[{"name":"test","inchikey":"ADVPTQAUNPRNPO-UHFFFAOYSA-N","retentiontime":11111,"theoretical":11,"massspectra":"111:1 112:2 113:3"},{"name":"test","inchikey":"ADVPTQAUNPRNPO-UHFFFAOYSA-N","retentiontime":11111,"theoretical":11,"massspectra":"111:1 112:2 113:3"}]}
        
        """).extract[CompoundWapper]

    compounds.compound.foreach { x: JsonCompound =>
      println(x)
    }
    
    
    null
  }

}

object WebserviceLibraryReader {

  def main(ars: Array[String]) = {
    println(new WebserviceLibraryReader().fetchCompounds("http://localhost:8080/alchemy-admin/services/queryAllCompoundsForMethod/test"))
  }
}

The complete tutorial can be found here

Wednesday, November 30, 2011

scala and instanceOf -

I'm for some reason a fan of instanceOf in java and just love to be able to check at runtime of what kind a class is and do some action depending on this outcome.

But sometimes it's a bit tedios. For example



Object a = new String("tada");
Object result = null;

if(a instanceOf Number){
result = "its a number";
}
else if(a instanceOf String){
result = "its a string";
}


System.out.println(result);



ok it's a silly example, now the pretty scala approach using match



var a:Any = "tada..."

val result = a match {
case n:Number => "it's a number"
case s:String => "it's a string"
}
println(result)



oh so pretty and easy to read.

Monday, November 28, 2011

casting and scala

since a couple of month's I work more and more with scala and really start to like this language. But some of the concepts are really confusing and make me wounder if this really is necceasary.

A prime example would be the whole casting of variables.

In java you simple do:


String value = (String)object;


now in scala


val value:String = object.asInstanceOf[String]


now I admit it looks very clean, but sure took a while to find this one little details.

Otherwise it's always better to use matchers.

Monday, March 1, 2010

scala/groovy on rocks linux

well since there is not scala/groovy roll for rocks we need to install it the traditional way.

  • go into the directory /shared/apps on the frontend
  • if apps doesn't exist create it
  • copy your scala/groovy tgz there
  • gunzip and untar it
  • edit your extend-compute.xml as shown here
  • add a new file modification section like this


<file name="/etc/profile" mode="append">

GROOVY_HOME=/share/apps/groovy
SCALA_HOME=/share/apps/scala

export GROOVY_HOME
export SCALA_HOME

PATH=$GROOVY_HOME/bin:$PATH
PATH=$SCALA_HOME/bin:$PATH

export PATH

</file>


  • rebuild your dist as shown here
  • reinstall you nodes as shown here

Monday, July 20, 2009

scala in grails

I know it's evil and I know you don't want todo this, but what the heck. This plugin allows you to compile and use scala code in grails.

I don't know why I would want to use scala right now in this, but I'm sure I find out a reason or two :)