1. Groovy: Efficiency Oriented Programming
Lecture 2
Master Proteomics & Bioinformatics - University of Geneva
Alexandre Masselot - summer 2010
2. Contents
• Eclipse IDE basics
• Assertions
• Closures
• I/O
• Functions
• Control structures
3. Eclipse IDE
• Eclipse is mainly known as a versatile Integrated Development
Environment (http://eclipse.org) although it can be much more
4. Eclipse IDE
• Eclipse is mainly known as a versatile Integrated Development
Environment (http://eclipse.org) although it can be much more
• Eclipse IDE itself is a naked framework, enriched by plugins
5. Eclipse IDE
• Eclipse is mainly known as a versatile Integrated Development
Environment (http://eclipse.org) although it can be much more
• Eclipse IDE itself is a naked framework, enriched by plugins
• We will use the prepackaged Springsource Tool Suite (http://
www.springsource.com/products/sts)
• start STS
• help > dashboard,
• tab extensions
• install groovy and grails
• restart eclipse
6. Eclipse IDE
• Eclipse is mainly known as a versatile Integrated Development
Environment (http://eclipse.org) although it can be much more
• Eclipse IDE itself is a naked framework, enriched by plugins
• We will use the prepackaged Springsource Tool Suite (http://
www.springsource.com/products/sts)
• start STS
• help > dashboard,
• tab extensions
• install groovy and grails
• restart eclipse
• Plenty of other plugins can be installed Help > Install new software
7. Eclipse IDE : a super simple setup
• starting eclipse => run into a workspace, i.e. a disk directory
8. Eclipse IDE : a super simple setup
• starting eclipse => run into a workspace, i.e. a disk directory
• one workspace hosts projects (sub directory strcture)
9. Eclipse IDE : a super simple setup
• starting eclipse => run into a workspace, i.e. a disk directory
• one workspace hosts projects (sub directory strcture)
• create a project New > Project > Groovy
10. Eclipse IDE : a super simple setup
• starting eclipse => run into a workspace, i.e. a disk directory
• one workspace hosts projects (sub directory strcture)
• create a project New > Project > Groovy
• You can change the workspace when working for totally different aspect of
a project (e.g. one for practicals, one for a more lab internship)
11. Eclipse IDE : a super simple setup
• a project contains several directories
12. Eclipse IDE : a super simple setup
• a project contains several directories
• src/ for the source file (the code you type)
13. Eclipse IDE : a super simple setup
• a project contains several directories
• src/ for the source file (the code you type)
• bin/ where the compiler write machine ready files
14. Eclipse IDE : a super simple setup
• a project contains several directories
• src/ for the source file (the code you type)
• bin/ where the compiler write machine ready files
• test/ where the test files (will) resides
15. Eclipse IDE : a super simple setup
• a project contains several directories
• src/ for the source file (the code you type)
• bin/ where the compiler write machine ready files
• test/ where the test files (will) resides
• lib/ etc.
16. Eclipse IDE : a super simple setup
• a project contains several directories
• src/ for the source file (the code you type)
• bin/ where the compiler write machine ready files
• test/ where the test files (will) resides
• lib/ etc.
• In the src directory, you can create packages. Package names are
delimiteid with dot e.g. mpb.practicals.lec1
17. Eclipse IDE : a super simple setup
• a project contains several directories
• src/ for the source file (the code you type)
• bin/ where the compiler write machine ready files
• test/ where the test files (will) resides
• lib/ etc.
• In the src directory, you can create packages. Package names are
delimiteid with dot e.g. mpb.practicals.lec1
• In practice, you will find a directory src/mpb/praticals/lec1/
19. Eclipse IDE : a super simple setup
• Then, you can create a new script : New > File > MyScript.groovy
20. Eclipse IDE : a super simple setup
• Then, you can create a new script : New > File > MyScript.groovy
• Run the script with Right button > Run as > groovy script
24. Assertions
To check a code validity, one solution is to call print statements
List l=[1, 2, 7, 4]
def x=l.max()
println “max is $x”
25. Assertions
To check a code validity, one solution is to call print statements
List l=[1, 2, 7, 4]
def x=l.max()
println “max is $x”
Relies on human reading...
28. Assertions
Use assertions that will clearly report failure if any, and be silent if none
assert x == 7
Any boolean value can be tested
assert [1, 7, 4] == l-2
assert “my funny valentine” == my_song
29. Assertions
Use assertions that will clearly report failure if any, and be silent if none
assert x == 7
Any boolean value can be tested
assert [1, 7, 4] == l-2
assert “my funny valentine” == my_song
assert statement are heavily used in test driven programming
41. Closures
“Let’s start with a simple definition of closures[...]. A closure is a piece of code
wrapped up as an object[...]. It’s a normal object in that you can pass a
reference to it around just as you can a reference to any other object”
(Groovy in Action - 5.1 A gentle introduction to closures)
42. Closures
“Let’s start with a simple definition of closures[...]. A closure is a piece of code
wrapped up as an object[...]. It’s a normal object in that you can pass a
reference to it around just as you can a reference to any other object”
(Groovy in Action - 5.1 A gentle introduction to closures)
Closure is a master feature of the groovy language. Although it can be used
in complex situations, closure are also part of daily programming.
43. Closures
It can be seen as a method attached to an object
List l=[1, 1, 2, 3, 5, 8, 13]
l.each{println it} //it is the default iterator
44. Closures
It can be seen as a method attached to an object
List l=[1, 1, 2, 3, 5, 8, 13]
l.each{println it} //it is the default iterator
The iterator can also be named
l.each{myVal -> println “value $myVal”}
“my funny valentine”.each{println $it} // -> m
// y ...
45. Closures (cont’d)
Much more closures are available on list
l.eachWithIndex{val, i -> println “list[$i]=$val”}
46. Closures (cont’d)
Much more closures are available on list
l.eachWithIndex{val, i -> println “list[$i]=$val”}
Find even values
l.findAll{ it%2 == 0} // -> [2, 8]
47. Closures (cont’d)
Much more closures are available on list
l.eachWithIndex{val, i -> println “list[$i]=$val”}
Find even values
l.findAll{ it%2 == 0} // -> [2, 8]
Make global boolean test
l.every{ it < 20 } // -> true (all values are <20)
l.any{ it < 0 } // -> false (none is negative)
48. Closures (cont’d)
Much more closures are available on list
l.eachWithIndex{val, i -> println “list[$i]=$val”}
Find even values
l.findAll{ it%2 == 0} // -> [2, 8]
Make global boolean test
l.every{ it < 20 } // -> true (all values are <20)
l.any{ it < 0 } // -> false (none is negative)
Transform
l.collect{ it*10} // [10, 10, 20 , 30, 50, ...]
49. Closures (cont’d)
Much more closures are available on list
l.eachWithIndex{val, i -> println “list[$i]=$val”}
Find even values
l.findAll{ it%2 == 0} // -> [2, 8]
Make global boolean test
l.every{ it < 20 } // -> true (all values are <20)
l.any{ it < 0 } // -> false (none is negative)
Transform
l.collect{ it*10} // [10, 10, 20 , 30, 50, ...]
Or even piped
l.findAll{ it%2 == 0}.collect{ it*10 } // -> [20, 80]
51. Closures (on map)
Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’),
‘simone’:new Date(‘4/2/1985’),
‘birgit’:new Date(’12/6/1988’)]
A simple loop
birthdays.each{
println “${it.key} born in “ + it.value.year
}
52. Closures (on map)
Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’),
‘simone’:new Date(‘4/2/1985’),
‘birgit’:new Date(’12/6/1988’)]
A simple loop
birthdays.each{
println “${it.key} born in “ + it.value.year
}
Or with name parameters
birthday.each{name, date -> println “$name : $date”}
53. Closures (on map)
Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’),
‘simone’:new Date(‘4/2/1985’),
‘birgit’:new Date(’12/6/1988’)]
A simple loop
birthdays.each{
println “${it.key} born in “ + it.value.year
}
Or with name parameters
birthday.each{name, date -> println “$name : $date”}
Sort on the month order
birthdays.sort{it.value.month}
.each{println “${it.key} born in “ + it.value}
54. I/O : reading standard input
Without any connection to outside, a script is soon meaningless...
55. I/O : reading standard input
Without any connection to outside, a script is soon meaningless...
Reading can be done from stdin (standard input)
System.in.eachLine{ ... } // loop on all line piped in
56. I/O : reading standard input
Without any connection to outside, a script is soon meaningless...
Reading can be done from stdin (standard input)
System.in.eachLine{ ... } // loop on all line piped in
Or interactively
Scanner stdin=new Scanner(System.in)
int i=stdin.nextInt()
stdin.<CTRL-space>
58. I/O: reading from Files
File myFile=new File(“path/to/my/file”)
Loop through the lines
myFile.eachLine{...}
myFile.splitEachLine(/s+/){
// it is an array with all
// the elements of the current line
}
59. I/O: reading from Files
File myFile=new File(“path/to/my/file”)
Loop through the lines
myFile.eachLine{...}
myFile.splitEachLine(/s+/){
// it is an array with all
// the elements of the current line
}
Or get the total text at once
myFile.getText()
60. I/O: reading from Files
File myFile=new File(“path/to/my/file”)
Loop through the lines
myFile.eachLine{...}
myFile.splitEachLine(/s+/){
// it is an array with all
// the elements of the current line
}
Or get the total text at once
myFile.getText()
Temporary file are often necessary
File myTmpFile=File.createTempFile(‘prefix’, ‘.suf’)
myTmpFile.deleteOnExit()
61. Functions
Function is a piece of code that takes argument and returns a value (like a
sub in perl)
62. Functions
Function is a piece of code that takes argument and returns a value (like a
sub in perl)
Parameters can be statically or dynamically typed
int increment(x, i){
return x+i
}
int j=3
println increment(j, 5) // -> 8
68. Functions (cont’d)
Number of arguments induces the function called
int increment (x, i){ return x+i }
int increment (x) { return x+1 }
println increment(3) // -> 4
println increment(3, 4) // -> 7
More concisely, parameters can be defined by default
int increment(x, i=1){ // if no second arg => i=1
return x+i
}
println increment(3, 5) // -> 8
println increment(3) // -> 4
69. Functions (cont’d)
Number of arguments induces the function called
int increment (x, i){ return x+i }
int increment (x) { return x+1 }
println increment(3) // -> 4
println increment(3, 4) // -> 7
More concisely, parameters can be defined by default
int increment(x, i=1){ // if no second arg => i=1
return x+i
}
println increment(3, 5) // -> 8
println increment(3) // -> 4
70. Functions (cont’d)
Number of arguments induces the function called
int increment (x, i){ return x+i }
int increment (x) { return x+1 }
println increment(3) // -> 4
println increment(3, 4) // -> 7
More concisely, parameters can be defined by default
int increment(x, i=1){ // if no second arg => i=1
return x+i
}
println increment(3, 5) // -> 8
println increment(3) // -> 4
71. Functions (cont’d)
Number of arguments induces the function called
int increment (x, i){ return x+i }
int increment (x) { return x+1 }
println increment(3) // -> 4
println increment(3, 4) // -> 7
More concisely, parameters can be defined by default
int increment(x, i=1){ // if no second arg => i=1
return x+i
}
println increment(3, 5) // -> 8
println increment(3) // -> 4
72. Functions (cont’d)
We can always use a Map with for named parameters
int increment(params){
return (params.x?:0) + // ?:0 0 if params.x false
(params.plus?:0) -
(params.minus?:0)
}
increment(x:3, plus:4) // -> 7
73. Functions (cont’d)
We can always use a Map with for named parameters
int increment(params){
return (params.x?:0) + // ?:0 0 if params.x false
(params.plus?:0) -
(params.minus?:0)
}
increment(x:3, plus:4) // -> 7
Method described fully with map arguments will be extensively used when
calling action from url
Notes de l'éditeur
\n
IDE basics\nhorizontal layers for learning\nmotto of the semester : keep the code concise!!\nwe&#x2019;ll focus on features of less than 10 lines. (->7)\n\n
Try plugins (tasks etc...)\nbut exp => do not mix too much . install eclipse in different directories\nuse shortcuts!!!\ncustomize them. Little mouse. we&#x2019;ll see the most useful shortcuts bit by bit\n\n
Try plugins (tasks etc...)\nbut exp => do not mix too much . install eclipse in different directories\nuse shortcuts!!!\ncustomize them. Little mouse. we&#x2019;ll see the most useful shortcuts bit by bit\n\n
Try plugins (tasks etc...)\nbut exp => do not mix too much . install eclipse in different directories\nuse shortcuts!!!\ncustomize them. Little mouse. we&#x2019;ll see the most useful shortcuts bit by bit\n\n
Try plugins (tasks etc...)\nbut exp => do not mix too much . install eclipse in different directories\nuse shortcuts!!!\ncustomize them. Little mouse. we&#x2019;ll see the most useful shortcuts bit by bit\n\n
(+ some meta-information) \nsetup will greatly be enhanced when we will build more than just scripts\nCTRL-Shift-F11 (or something close, depending on your setup) to relaunch the script\nCtrl-space demo\ndon&#x2019;t forget to close project to limit noise\n
(+ some meta-information) \nsetup will greatly be enhanced when we will build more than just scripts\nCTRL-Shift-F11 (or something close, depending on your setup) to relaunch the script\nCtrl-space demo\ndon&#x2019;t forget to close project to limit noise\n
(+ some meta-information) \nsetup will greatly be enhanced when we will build more than just scripts\nCTRL-Shift-F11 (or something close, depending on your setup) to relaunch the script\nCtrl-space demo\ndon&#x2019;t forget to close project to limit noise\n
(+ some meta-information) \nsetup will greatly be enhanced when we will build more than just scripts\nCTRL-Shift-F11 (or something close, depending on your setup) to relaunch the script\nCtrl-space demo\ndon&#x2019;t forget to close project to limit noise\n
do not touch build/ explicitely\n
do not touch build/ explicitely\n
do not touch build/ explicitely\n
do not touch build/ explicitely\n
do not touch build/ explicitely\n
do not touch build/ explicitely\n
do not touch build/ explicitely\n
we will come back often to discover more possibilities in using eclipse...\ndon&#x2019;t forget to close project to limit noise\n
we will come back often to discover more possibilities in using eclipse...\ndon&#x2019;t forget to close project to limit noise\n
we will come back often to discover more possibilities in using eclipse...\ndon&#x2019;t forget to close project to limit noise\n
\n
\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
go google!!!\nWe will be always able to see a 1% of the possibilities\n
go google!!!\nWe will be always able to see a 1% of the possibilities\n
go google!!!\nWe will be always able to see a 1% of the possibilities\n
go google!!!\nWe will be always able to see a 1% of the possibilities\n
go google!!!\nWe will be always able to see a 1% of the possibilities\n
see the new Date(string)\nbirthday.each -> loop on Map Entry (key/value)\nin fact, a linkedMap (order is kept)\nhow to sort with decreasing month (dec, nov,...january)\n
see the new Date(string)\nbirthday.each -> loop on Map Entry (key/value)\nin fact, a linkedMap (order is kept)\nhow to sort with decreasing month (dec, nov,...january)\n
see the new Date(string)\nbirthday.each -> loop on Map Entry (key/value)\nin fact, a linkedMap (order is kept)\nhow to sort with decreasing month (dec, nov,...january)\n
see the new Date(string)\nbirthday.each -> loop on Map Entry (key/value)\nin fact, a linkedMap (order is kept)\nhow to sort with decreasing month (dec, nov,...january)\n
often have automated reading through file \nparameters are passed as command arguments or into a file\n
often have automated reading through file \nparameters are passed as command arguments or into a file\n
often have automated reading through file \nparameters are passed as command arguments or into a file\n
don&#x2019;t forget that most of the commons manipulations are already programmed in the core library\nFile delete, exist, find all file names etc.. \n
don&#x2019;t forget that most of the commons manipulations are already programmed in the core library\nFile delete, exist, find all file names etc.. \n
don&#x2019;t forget that most of the commons manipulations are already programmed in the core library\nFile delete, exist, find all file names etc.. \n
don&#x2019;t forget that most of the commons manipulations are already programmed in the core library\nFile delete, exist, find all file names etc.. \n