SlideShare a Scribd company logo
©ASERT2006-2013
Dr Paul King @paulk_asert
Director, ASERT, Brisbane, Australia
http:/slideshare.net/paulk_asert/tictactoe-groovy
https://github.com/paulk-asert/tictactoe-groovy
Coding TicTacToe:
A coding style
challenge!
** Coming
soon!
Topics
Introduction
• Dynamic solution
• Options for increasing type safety
• Groovy challenge solution
• Other language implementations
• Interlude: solving tic tac toe
• Going beyond the challenge
©ASERT2006-2013
Tic Tac Toe
• Players take it in turn to
place “marks” on the
board
• By convention, Player 1
uses “X” and starts
first; Player 2 uses “O”
• The game finishes once
one of the players has
three of their marks in a
row
• Also called noughts
and crosses (and other
names) with 4 x 4, 3D
and other variants
Challenge: Tic Tac Toe API
• move: given a board and position returns a
board with the current player at that position
– Can only be called on a board that is in-play; calling move on a
game board that is finished is a compile-time type error
• whoWon: given a finished board indicates if the
game was a draw or which player won
– Can only be called on a board that is finished; calling whoWon
on a game board that is in-play is a compile-time type error
• takeBack: takes either a finished board or a
board in-play that has had at least one move
and returns a board in-play
– It is a compile-time type error when used on an empty board
• playerAt: takes any board and position and
returns the (possible) player at the position
The main example for this talk is based on and inspired by:
https://github.com/tonymorris/course-answers/blob/master/src/TicTacToe/TicTacToe.md
But what’s this talk really about?
• Not really about solving/coding TicTacToe
• Looking at the Dynamic <-> Static typing
spectrum
• Looking at the OO <-> functional style
spectrum
• Looking at the pros and cons of different
programming styles
But what’s this talk really about?
• We all have the same goal
–Productively writing “bug-free”
maintainable code that “solves” some
real world users problem
–Types are one trick in my toolkit but I
also have tests, invariants
–Numerous ways to benefit from types
–Types are a burden on the programmer
–When writing DSLs, certain scripts,
certain test code, types may not justify
the burden
…DSL example...
©ASERT2006-2012
class FluentApi {
def action, what
def the(what) { this.what = what; this }
def of(arg) { action(what(arg)) }
}
show = { arg -> println arg }
square_root = { Math.sqrt(it) }
please = { new FluentApi(action: it) }
please show the square_root of 100 // => 10.0
DSL usage
…DSL example...
©ASERT2006-2012
please show the square_root of 100
please(show).the(square_root).of(100)
Inspiration for this example came from …
...DSL example
©ASERT2006-2012
// Japanese DSL using GEP3 rules
Object.metaClass.を =
Object.metaClass.の =
{ clos -> clos(delegate) }
まず = { it }
表示する = { println it }
平方根 = { Math.sqrt(it) }
まず 100 の 平方根 を 表示する
// First, show the square root of 100
// => 10.0
source: http://d.hatena.ne.jp/uehaj/20100919/1284906117
also: http://groovyconsole.appspot.com/edit/241001
Topics
• Introduction
Dynamic solution
• Options for increasing type safety
• Groovy challenge solution
• Other language implementations
• Interlude: solving tic tac toe
• Going beyond the challenge
©ASERT2006-2013
Show me the code
DynamicTTT.groovy
Topics
• Introduction
• Dynamic solution
Options for increasing type safety
• Groovy challenge solution
• Other language implementations
• Interlude: solving tic tac toe
• Going beyond the challenge
©ASERT2006-2013
Java Typing limitations
long freezingC = 0 // 0 °C
long boilingF = 212 // 212 °F
long delta = boilingF - freezingC
long heavy = 100 // 100 kg
Using JScience
@GrabResolver('http://maven.obiba.org/maven2')
@Grab('org.jscience:jscience:4.3.1')
import ...
//@TypeChecked
def main() {
Amount<Temperature> freezingC = valueOf(0L, CELSIUS)
def boilingF = valueOf(212L, FAHRENHEIT)
printDifference(boilingF, freezingC)
def heavy = valueOf(100L, KILO(GRAM))
printDifference(heavy, boilingF)
}
def <T> void printDifference(Amount<T> arg1, Amount<T> arg2) {
println arg1 - arg2
}
(180.00000000000006 ± 1.4E-14) °F
javax.measure.converter.ConversionException: °F is
not compatible with kg
Using JScience & @TypeChecked
...
@TypeChecked
def main() {
Amount<Temperature> freezingC = valueOf(0L, CELSIUS)
def boilingF = valueOf(212L, FAHRENHEIT)
printDifference(boilingF, freezingC)
def heavy = valueOf(100L, KILO(GRAM))
printDifference(heavy, boilingF)
}
def <T> void printDifference(Amount<T> arg1, Amount<T> arg2) {
println arg1 - arg2
}
[Static type checking] - Cannot call
ConsoleScript46#printDifference(org.jscience.physics.amount.Amount
<T>, org.jscience.physics.amount.Amount <T>) with arguments
[org.jscience.physics.amount.Amount <javax.measure.quantity.Mass>,
org.jscience.physics.amount.Amount
<javax.measure.quantity.Temperature>]
Mars Orbiter (artists impression)
…Typing…
import groovy.transform.TypeChecked
import experimental.SprintfTypeCheckingVisitor
@TypeChecked(visitor=SprintfTypeCheckingVisitor)
void main() {
sprintf('%s will turn %d on %tF', 'John', new Date(), 21)
}
[Static type checking] - Parameter types didn't match types
expected from the format String:
For placeholder 2 [%d] expected 'int' but was 'java.util.Date'
For placeholder 3 [%tF] expected 'java.util.Date' but was 'int'
sprintf has an Object varargs
parameter, hence not normally
amenable to further static checking
but for constant Strings we can do
better using a custom type checking
plugin.
Show me the code
Type safe builder, phantom types, dependent types: Rocket, HList
©ASERT2006-2012
GContracts
@Grab('org.gcontracts:gcontracts-core:1.2.10')
import org.gcontracts.annotations.*
@Invariant({ speed >= 0 })
class Rocket {
@Requires({ !started })
@Ensures({ started })
def start() { /* ... */ }
@Requires({ started })
@Ensures({ old.speed < speed })
def accelerate() { /* ... */ }
/* ... */
}
def r = new Rocket()
r.start()
r.accelerate()
Topics
• Introduction
• Dynamic solution
• Options for increasing type safety
Groovy challenge solution
• Other language implementations
• Interlude: solving tic tac toe
• Going beyond the challenge
©ASERT2006-2013
Show me the code
TicTacToe
Topics
• Introduction
• Dynamic solution
• Options for increasing type safety
• Groovy challenge solution
Other language implementations
• Interlude: solving tic tac toe
• Going beyond the challenge
©ASERT2006-2013
Show me the code
Haskell, Scala
Topics
• Introduction
• Dynamic solution
• Options for increasing type safety
• Groovy challenge solution
• Other language implementations
Interlude: solving tic tac toe
• Going beyond the challenge
©ASERT2006-2013
Interlude: Solving Tic Tac Toe
• Use a game tree to
map out all possible
moves
• Solve the game tree
using brute force or
with various
optimisation
algorithms
Interlude: Tic Tac Toe game tree
Source: http://en.wikipedia.org/wiki/Game_tree
Interlude: Tic Tac Toe game tree
• Brute force
• Minimax
– Reduced
lookahead, e.g.
2 layers/plies
• Alpha beta pruning
– Improved efficiency
• Iterative deepening
– Often used with
alpha beta pruning
• But for Tic Tac Toe only 100s of
end states and 10s of thousands
of paths to get there
Source: http://en.wikipedia.org/wiki/Game_tree
Topics
• Introduction
• Dynamic solution
• Options for increasing type safety
• Groovy challenge solution
• Other language implementations
• Interlude: solving tic tac toe
Going beyond the challenge
©ASERT2006-2013
Static Type Checking: Pluggable type system…
import groovy.transform.TypeChecked
import checker.BoringNameEliminator
@TypeChecked(visitor=BoringNameEliminator)
class Foo {
def method1() { 1 }
}
import groovy.transform.TypeChecked
import checker.BoringNameEliminator
@TypeChecked(visitor=BoringNameEliminator)
class Foo {
def method() { 1 }
}
[Static type checking] - Your method name is boring, I cannot allow it!
Groovy 2.1+
…Static Type Checking: Pluggable type system
package checker
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.transform.stc.*
class BoringNameEliminator extends StaticTypeCheckingVisitor {
BoringNameEliminator(SourceUnit source, ClassNode cn,
TypeCheckerPluginFactory pluginFactory) {
super(source, cn, pluginFactory)
}
final message = "Your method name is boring, I cannot allow it!"
@Override void visitMethod(MethodNode node) {
super.visitMethod(node)
if ("method".equals(node.name) || "bar".equals(node.name)) {
addStaticTypeError(message, node)
}
}
}
Groovy 2.1+
…Typing…
import groovy.transform.TypeChecked
import tictactoe.*
Import static tictactoe.Position.*
@TypeChecked(visitor=TicTacToeTypeVisitor)
void main() {
Board.empty().move(NW).move(C).move(W).move(SW).move(SE)
}
package tictactoe
enum Position {
NW, N, NE, W, C, E, SW, S, SE
}
class Board {
static Board empty() { new Board() }
Board move(Position p) { this }
}
…Typing…
package tictactoe
import fj.*
import fj.data.List
import fj.data.Option
import fj.data.TreeMap
import static fj.P.p
import static fj.data.List.list
import static fj.data.List.nil
import static fj.data.Option.none
import static tictactoe.GameResult.Draw
import static tictactoe.Player.Player1
import static tictactoe.Player.toSymbol
import static tictactoe.Position.*
final class Board extends BoardLike {
private final List<P2<Position, Player>> moves
private final TreeMap<Position, Player> m
private static final Ord<Position> positionOrder = Ord.comparableOrd()
private Board(final List<P2<Position, Player>> moves, final TreeMap<Position, Player> m) {
this.moves = moves
this.m = m
}
Player whoseTurn() { moves.head()._2().alternate() }
boolean isEmpty() { false }
List<Position> occupiedPositions() { m.keys() }
int nmoves() { m.size() }
Option<Player> playerAt(Position pos) { m.get(pos) }
TakenBack takeBack() {
moves.isEmpty() ?
TakenBack.isEmpty() :
TakenBack.isBoard(new Board(moves.tail(), m.delete(moves.head()._1())))
}
@SuppressWarnings("unchecked")
MoveResult moveTo(final Position pos) {
final Player wt = whoseTurn()
final Option<Player> j = m.get(pos)
final TreeMap<Position, Player> mm = m.set(pos, wt)
final Board bb = new Board(moves.cons(p(pos, wt)), mm)
final List<P3<Position, Position, Position>> wins =
list(
p(NW, W, SW), p(N, C, S), p(NE, E, SE), p(NW, N, NE),
p(W, C, E), p(SW, S, SE), p(NW, C, SE), p(SW, C, NE)
)
final boolean isWin = wins.exists(new F<P3<Position, Position, Position>, Boolean>() {
public Boolean f(final P3<Position, Position, Position> abc) {
return list(abc._1(), abc._2(), abc._3()).mapMOption(mm.get()).exists(new F<List<Player>, Boolean>() {
public Boolean f(final List<Player> ps) {
return ps.allEqual(Equal.<Player> anyEqual())
}
})
}
})
final boolean isDraw = Position.positions().forall(new F<Position, Boolean>() {
Boolean f(final Position pos2) {
mm.contains(pos2)
}
})
j.isSome() ?
MoveResult.positionAlreadyOccupied() :
isWin ?
MoveResult.gameOver(new FinishedBoard(bb, GameResult.win(wt))) :
isDraw ?
MoveResult.gameOver(new FinishedBoard(bb, Draw)) :
MoveResult.keepPlaying(bb)
}
// …
// …
@Override
String toString() {
toString(new F2<Option<Player>, Position, Character>() {
Character f(final Option<Player> pl, final Position _) {
pl.option(p(' '), toSymbol)
}
}) + "n[ " + whoseTurn().toString() + " to move ]"
}
static final class EmptyBoard extends BoardLike {
private EmptyBoard() {}
@SuppressWarnings("unchecked")
Board moveTo(final Position pos) {
new Board(list(p(pos, Player1)), TreeMap.<Position, Player> empty(positionOrder).set(pos, Player1))
}
private static final EmptyBoard e = new EmptyBoard()
static EmptyBoard empty() { e }
Player whoseTurn() { Player1 }
boolean isEmpty() { true }
List<Position> occupiedPositions() { nil() }
int nmoves() { 0 }
Option<Player> playerAt(Position pos) { none() }
}
static final class FinishedBoard extends BoardLike {
private final Board b
private final GameResult r
private FinishedBoard(final Board b, final GameResult r) {
this.b = b
this.r = r
}
Board takeBack() {
b.takeBack().fold(
Bottom.<Board> error_("Broken invariant: board in-play with empty move list. This is a program bug"),
Function.<Board> identity()
)
}
Player whoseTurn() { b.whoseTurn() }
boolean isEmpty() { false }
List<Position> occupiedPositions() { b.occupiedPositions() }
int nmoves() { b.nmoves() }
Option<Player> playerAt(final Position pos) { b.playerAt(pos) }
GameResult result() { r }
@Override
String toString() {
b.toString() + "n[[" + r.toString() + " ]]"
}
}
}
…Typing
import groovy.transform.TypeChecked
import tictactoe.*
Import static tictactoe.Position.*
@TypeChecked(visitor=TicTacToeTypeVisitor)
void main() {
Board.empty().move(NW).move(C).move(W).move(SW).move(SE)
}
package tictactoe
enum Position {
NW, N, NE, W, C, E, SW, S, SE
}
[Static type checking] - Attempt to call suboptimal
move SE not allowed [HINT: try NE]
Custom type checker which fails
compilation if programmer attempts
to code a suboptimal solution. Where
suboptimal means doesn’t agree with
what is returned by a minimax,
alpha-beta pruning, iterative
deepening solving engine.
Show me the code
More Information: Groovy in Action

More Related Content

What's hot

Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
Arturo Herrero
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
functional groovy
functional groovyfunctional groovy
functional groovyPaul King
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
Gagan Agrawal
 
Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspective
Norman Richards
 
Oleksii Holub "Expression trees in C#"
Oleksii Holub "Expression trees in C#" Oleksii Holub "Expression trees in C#"
Oleksii Holub "Expression trees in C#"
Fwdays
 
Gpars concepts explained
Gpars concepts explainedGpars concepts explained
Gpars concepts explained
Vaclav Pech
 
Expression trees in C#
Expression trees in C#Expression trees in C#
Expression trees in C#
Oleksii Holub
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GPars
Paul King
 
Polyglot Grails
Polyglot GrailsPolyglot Grails
Polyglot Grails
Marcin Gryszko
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
Norman Richards
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
Zaar Hai
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)
Ken Kousen
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in Groovy
Jim Driscoll
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8conf
GR8Conf
 
A gremlin in my graph confoo 2014
A gremlin in my graph confoo 2014A gremlin in my graph confoo 2014
A gremlin in my graph confoo 2014
Damien Seguy
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 

What's hot (20)

Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
functional groovy
functional groovyfunctional groovy
functional groovy
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
 
Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspective
 
Oleksii Holub "Expression trees in C#"
Oleksii Holub "Expression trees in C#" Oleksii Holub "Expression trees in C#"
Oleksii Holub "Expression trees in C#"
 
Gpars concepts explained
Gpars concepts explainedGpars concepts explained
Gpars concepts explained
 
Expression trees in C#
Expression trees in C#Expression trees in C#
Expression trees in C#
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GPars
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
 
Polyglot Grails
Polyglot GrailsPolyglot Grails
Polyglot Grails
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in Groovy
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8conf
 
A gremlin in my graph confoo 2014
A gremlin in my graph confoo 2014A gremlin in my graph confoo 2014
A gremlin in my graph confoo 2014
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 

Viewers also liked

Rhythm tic tac-toe
Rhythm tic tac-toeRhythm tic tac-toe
Rhythm tic tac-toe
dlynn525
 
Littlebits Tic Tac Toe
Littlebits Tic Tac ToeLittlebits Tic Tac Toe
Littlebits Tic Tac ToeJennifer Lewis
 
Tic tac toe
Tic tac toeTic tac toe
Tic tac toe
Syeda Urooba
 
Tic Tac Presentation
Tic Tac PresentationTic Tac Presentation
Tic Tac Presentationgupsaurabh
 
TIC TAC TOE
TIC TAC TOETIC TAC TOE
TIC TAC TOE
asmhemu
 
Tic tac toe simple ai game
Tic tac toe simple ai gameTic tac toe simple ai game
Tic tac toe simple ai game
Seevaratnam Kajandan
 
Tic tac toe c++ project presentation
Tic tac toe c++ project presentationTic tac toe c++ project presentation
Tic tac toe c++ project presentationSaad Symbian
 
Game project Final presentation
Game project Final presentationGame project Final presentation
Game project Final presentationgemmalunney
 
Final project report of a game
Final project report of a gameFinal project report of a game
Final project report of a game
Nadia Nahar
 

Viewers also liked (9)

Rhythm tic tac-toe
Rhythm tic tac-toeRhythm tic tac-toe
Rhythm tic tac-toe
 
Littlebits Tic Tac Toe
Littlebits Tic Tac ToeLittlebits Tic Tac Toe
Littlebits Tic Tac Toe
 
Tic tac toe
Tic tac toeTic tac toe
Tic tac toe
 
Tic Tac Presentation
Tic Tac PresentationTic Tac Presentation
Tic Tac Presentation
 
TIC TAC TOE
TIC TAC TOETIC TAC TOE
TIC TAC TOE
 
Tic tac toe simple ai game
Tic tac toe simple ai gameTic tac toe simple ai game
Tic tac toe simple ai game
 
Tic tac toe c++ project presentation
Tic tac toe c++ project presentationTic tac toe c++ project presentation
Tic tac toe c++ project presentation
 
Game project Final presentation
Game project Final presentationGame project Final presentation
Game project Final presentation
 
Final project report of a game
Final project report of a gameFinal project report of a game
Final project report of a game
 

Similar to tictactoe groovy

Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
Andres Almiray
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
Skills Matter
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
Rodolfo Carvalho
 
Groovy
GroovyGroovy
Groovy
Zen Urban
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
Robot Media
 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in Code
Eamonn Boyle
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
Cより速いRubyプログラム
Cより速いRubyプログラムCより速いRubyプログラム
Cより速いRubyプログラム
kwatch
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
Yakov Fain
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
Jonathan Felch
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Víctor Bolinches
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
Andres Almiray
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyJames Williams
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
Tugdual Grall
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
Matt Stine
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Tudor Dragan
 

Similar to tictactoe groovy (20)

Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Groovy
GroovyGroovy
Groovy
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in Code
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
 
Cより速いRubyプログラム
Cより速いRubyプログラムCより速いRubyプログラム
Cより速いRubyプログラム
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 

More from Paul King

groovy databases
groovy databasesgroovy databases
groovy databases
Paul King
 
Agile Testing Practices
Agile Testing PracticesAgile Testing Practices
Agile Testing Practices
Paul King
 
groovy DSLs from beginner to expert
groovy DSLs from beginner to expertgroovy DSLs from beginner to expert
groovy DSLs from beginner to expert
Paul King
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrency
Paul King
 
GroovyDSLs
GroovyDSLsGroovyDSLs
GroovyDSLs
Paul King
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
Paul King
 
Dynamic Language Practices
Dynamic Language PracticesDynamic Language Practices
Dynamic Language Practices
Paul King
 
Make Your Builds More Groovy
Make Your Builds More GroovyMake Your Builds More Groovy
Make Your Builds More Groovy
Paul King
 
Groovy Power Features
Groovy Power FeaturesGroovy Power Features
Groovy Power Features
Paul King
 
Make Your Testing Groovy
Make Your Testing GroovyMake Your Testing Groovy
Make Your Testing Groovy
Paul King
 
Groovy Testing Sep2009
Groovy Testing Sep2009Groovy Testing Sep2009
Groovy Testing Sep2009
Paul King
 
Craig Smith & Paul King Agile Tool Hacking Taking Your Agile Development ...
Craig Smith & Paul King   Agile Tool Hacking   Taking Your Agile Development ...Craig Smith & Paul King   Agile Tool Hacking   Taking Your Agile Development ...
Craig Smith & Paul King Agile Tool Hacking Taking Your Agile Development ...Paul King
 
Groovy Tutorial
Groovy TutorialGroovy Tutorial
Groovy Tutorial
Paul King
 
XML and Web Services with Groovy
XML and Web Services with GroovyXML and Web Services with Groovy
XML and Web Services with Groovy
Paul King
 

More from Paul King (14)

groovy databases
groovy databasesgroovy databases
groovy databases
 
Agile Testing Practices
Agile Testing PracticesAgile Testing Practices
Agile Testing Practices
 
groovy DSLs from beginner to expert
groovy DSLs from beginner to expertgroovy DSLs from beginner to expert
groovy DSLs from beginner to expert
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrency
 
GroovyDSLs
GroovyDSLsGroovyDSLs
GroovyDSLs
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Dynamic Language Practices
Dynamic Language PracticesDynamic Language Practices
Dynamic Language Practices
 
Make Your Builds More Groovy
Make Your Builds More GroovyMake Your Builds More Groovy
Make Your Builds More Groovy
 
Groovy Power Features
Groovy Power FeaturesGroovy Power Features
Groovy Power Features
 
Make Your Testing Groovy
Make Your Testing GroovyMake Your Testing Groovy
Make Your Testing Groovy
 
Groovy Testing Sep2009
Groovy Testing Sep2009Groovy Testing Sep2009
Groovy Testing Sep2009
 
Craig Smith & Paul King Agile Tool Hacking Taking Your Agile Development ...
Craig Smith & Paul King   Agile Tool Hacking   Taking Your Agile Development ...Craig Smith & Paul King   Agile Tool Hacking   Taking Your Agile Development ...
Craig Smith & Paul King Agile Tool Hacking Taking Your Agile Development ...
 
Groovy Tutorial
Groovy TutorialGroovy Tutorial
Groovy Tutorial
 
XML and Web Services with Groovy
XML and Web Services with GroovyXML and Web Services with Groovy
XML and Web Services with Groovy
 

Recently uploaded

GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 

tictactoe groovy

  • 1. ©ASERT2006-2013 Dr Paul King @paulk_asert Director, ASERT, Brisbane, Australia http:/slideshare.net/paulk_asert/tictactoe-groovy https://github.com/paulk-asert/tictactoe-groovy Coding TicTacToe: A coding style challenge! ** Coming soon!
  • 2. Topics Introduction • Dynamic solution • Options for increasing type safety • Groovy challenge solution • Other language implementations • Interlude: solving tic tac toe • Going beyond the challenge ©ASERT2006-2013
  • 3. Tic Tac Toe • Players take it in turn to place “marks” on the board • By convention, Player 1 uses “X” and starts first; Player 2 uses “O” • The game finishes once one of the players has three of their marks in a row • Also called noughts and crosses (and other names) with 4 x 4, 3D and other variants
  • 4. Challenge: Tic Tac Toe API • move: given a board and position returns a board with the current player at that position – Can only be called on a board that is in-play; calling move on a game board that is finished is a compile-time type error • whoWon: given a finished board indicates if the game was a draw or which player won – Can only be called on a board that is finished; calling whoWon on a game board that is in-play is a compile-time type error • takeBack: takes either a finished board or a board in-play that has had at least one move and returns a board in-play – It is a compile-time type error when used on an empty board • playerAt: takes any board and position and returns the (possible) player at the position The main example for this talk is based on and inspired by: https://github.com/tonymorris/course-answers/blob/master/src/TicTacToe/TicTacToe.md
  • 5. But what’s this talk really about? • Not really about solving/coding TicTacToe • Looking at the Dynamic <-> Static typing spectrum • Looking at the OO <-> functional style spectrum • Looking at the pros and cons of different programming styles
  • 6. But what’s this talk really about? • We all have the same goal –Productively writing “bug-free” maintainable code that “solves” some real world users problem –Types are one trick in my toolkit but I also have tests, invariants –Numerous ways to benefit from types –Types are a burden on the programmer –When writing DSLs, certain scripts, certain test code, types may not justify the burden
  • 7. …DSL example... ©ASERT2006-2012 class FluentApi { def action, what def the(what) { this.what = what; this } def of(arg) { action(what(arg)) } } show = { arg -> println arg } square_root = { Math.sqrt(it) } please = { new FluentApi(action: it) } please show the square_root of 100 // => 10.0 DSL usage
  • 8. …DSL example... ©ASERT2006-2012 please show the square_root of 100 please(show).the(square_root).of(100) Inspiration for this example came from …
  • 9. ...DSL example ©ASERT2006-2012 // Japanese DSL using GEP3 rules Object.metaClass.を = Object.metaClass.の = { clos -> clos(delegate) } まず = { it } 表示する = { println it } 平方根 = { Math.sqrt(it) } まず 100 の 平方根 を 表示する // First, show the square root of 100 // => 10.0 source: http://d.hatena.ne.jp/uehaj/20100919/1284906117 also: http://groovyconsole.appspot.com/edit/241001
  • 10. Topics • Introduction Dynamic solution • Options for increasing type safety • Groovy challenge solution • Other language implementations • Interlude: solving tic tac toe • Going beyond the challenge ©ASERT2006-2013
  • 11. Show me the code DynamicTTT.groovy
  • 12. Topics • Introduction • Dynamic solution Options for increasing type safety • Groovy challenge solution • Other language implementations • Interlude: solving tic tac toe • Going beyond the challenge ©ASERT2006-2013
  • 13. Java Typing limitations long freezingC = 0 // 0 °C long boilingF = 212 // 212 °F long delta = boilingF - freezingC long heavy = 100 // 100 kg
  • 14. Using JScience @GrabResolver('http://maven.obiba.org/maven2') @Grab('org.jscience:jscience:4.3.1') import ... //@TypeChecked def main() { Amount<Temperature> freezingC = valueOf(0L, CELSIUS) def boilingF = valueOf(212L, FAHRENHEIT) printDifference(boilingF, freezingC) def heavy = valueOf(100L, KILO(GRAM)) printDifference(heavy, boilingF) } def <T> void printDifference(Amount<T> arg1, Amount<T> arg2) { println arg1 - arg2 } (180.00000000000006 ± 1.4E-14) °F javax.measure.converter.ConversionException: °F is not compatible with kg
  • 15. Using JScience & @TypeChecked ... @TypeChecked def main() { Amount<Temperature> freezingC = valueOf(0L, CELSIUS) def boilingF = valueOf(212L, FAHRENHEIT) printDifference(boilingF, freezingC) def heavy = valueOf(100L, KILO(GRAM)) printDifference(heavy, boilingF) } def <T> void printDifference(Amount<T> arg1, Amount<T> arg2) { println arg1 - arg2 } [Static type checking] - Cannot call ConsoleScript46#printDifference(org.jscience.physics.amount.Amount <T>, org.jscience.physics.amount.Amount <T>) with arguments [org.jscience.physics.amount.Amount <javax.measure.quantity.Mass>, org.jscience.physics.amount.Amount <javax.measure.quantity.Temperature>]
  • 16. Mars Orbiter (artists impression)
  • 17. …Typing… import groovy.transform.TypeChecked import experimental.SprintfTypeCheckingVisitor @TypeChecked(visitor=SprintfTypeCheckingVisitor) void main() { sprintf('%s will turn %d on %tF', 'John', new Date(), 21) } [Static type checking] - Parameter types didn't match types expected from the format String: For placeholder 2 [%d] expected 'int' but was 'java.util.Date' For placeholder 3 [%tF] expected 'java.util.Date' but was 'int' sprintf has an Object varargs parameter, hence not normally amenable to further static checking but for constant Strings we can do better using a custom type checking plugin.
  • 18. Show me the code Type safe builder, phantom types, dependent types: Rocket, HList
  • 19. ©ASERT2006-2012 GContracts @Grab('org.gcontracts:gcontracts-core:1.2.10') import org.gcontracts.annotations.* @Invariant({ speed >= 0 }) class Rocket { @Requires({ !started }) @Ensures({ started }) def start() { /* ... */ } @Requires({ started }) @Ensures({ old.speed < speed }) def accelerate() { /* ... */ } /* ... */ } def r = new Rocket() r.start() r.accelerate()
  • 20. Topics • Introduction • Dynamic solution • Options for increasing type safety Groovy challenge solution • Other language implementations • Interlude: solving tic tac toe • Going beyond the challenge ©ASERT2006-2013
  • 21. Show me the code TicTacToe
  • 22. Topics • Introduction • Dynamic solution • Options for increasing type safety • Groovy challenge solution Other language implementations • Interlude: solving tic tac toe • Going beyond the challenge ©ASERT2006-2013
  • 23. Show me the code Haskell, Scala
  • 24. Topics • Introduction • Dynamic solution • Options for increasing type safety • Groovy challenge solution • Other language implementations Interlude: solving tic tac toe • Going beyond the challenge ©ASERT2006-2013
  • 25. Interlude: Solving Tic Tac Toe • Use a game tree to map out all possible moves • Solve the game tree using brute force or with various optimisation algorithms
  • 26. Interlude: Tic Tac Toe game tree Source: http://en.wikipedia.org/wiki/Game_tree
  • 27. Interlude: Tic Tac Toe game tree • Brute force • Minimax – Reduced lookahead, e.g. 2 layers/plies • Alpha beta pruning – Improved efficiency • Iterative deepening – Often used with alpha beta pruning • But for Tic Tac Toe only 100s of end states and 10s of thousands of paths to get there Source: http://en.wikipedia.org/wiki/Game_tree
  • 28. Topics • Introduction • Dynamic solution • Options for increasing type safety • Groovy challenge solution • Other language implementations • Interlude: solving tic tac toe Going beyond the challenge ©ASERT2006-2013
  • 29. Static Type Checking: Pluggable type system… import groovy.transform.TypeChecked import checker.BoringNameEliminator @TypeChecked(visitor=BoringNameEliminator) class Foo { def method1() { 1 } } import groovy.transform.TypeChecked import checker.BoringNameEliminator @TypeChecked(visitor=BoringNameEliminator) class Foo { def method() { 1 } } [Static type checking] - Your method name is boring, I cannot allow it! Groovy 2.1+
  • 30. …Static Type Checking: Pluggable type system package checker import org.codehaus.groovy.ast.* import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.transform.stc.* class BoringNameEliminator extends StaticTypeCheckingVisitor { BoringNameEliminator(SourceUnit source, ClassNode cn, TypeCheckerPluginFactory pluginFactory) { super(source, cn, pluginFactory) } final message = "Your method name is boring, I cannot allow it!" @Override void visitMethod(MethodNode node) { super.visitMethod(node) if ("method".equals(node.name) || "bar".equals(node.name)) { addStaticTypeError(message, node) } } } Groovy 2.1+
  • 31. …Typing… import groovy.transform.TypeChecked import tictactoe.* Import static tictactoe.Position.* @TypeChecked(visitor=TicTacToeTypeVisitor) void main() { Board.empty().move(NW).move(C).move(W).move(SW).move(SE) } package tictactoe enum Position { NW, N, NE, W, C, E, SW, S, SE } class Board { static Board empty() { new Board() } Board move(Position p) { this } }
  • 32. …Typing… package tictactoe import fj.* import fj.data.List import fj.data.Option import fj.data.TreeMap import static fj.P.p import static fj.data.List.list import static fj.data.List.nil import static fj.data.Option.none import static tictactoe.GameResult.Draw import static tictactoe.Player.Player1 import static tictactoe.Player.toSymbol import static tictactoe.Position.* final class Board extends BoardLike { private final List<P2<Position, Player>> moves private final TreeMap<Position, Player> m private static final Ord<Position> positionOrder = Ord.comparableOrd() private Board(final List<P2<Position, Player>> moves, final TreeMap<Position, Player> m) { this.moves = moves this.m = m } Player whoseTurn() { moves.head()._2().alternate() } boolean isEmpty() { false } List<Position> occupiedPositions() { m.keys() } int nmoves() { m.size() } Option<Player> playerAt(Position pos) { m.get(pos) } TakenBack takeBack() { moves.isEmpty() ? TakenBack.isEmpty() : TakenBack.isBoard(new Board(moves.tail(), m.delete(moves.head()._1()))) } @SuppressWarnings("unchecked") MoveResult moveTo(final Position pos) { final Player wt = whoseTurn() final Option<Player> j = m.get(pos) final TreeMap<Position, Player> mm = m.set(pos, wt) final Board bb = new Board(moves.cons(p(pos, wt)), mm) final List<P3<Position, Position, Position>> wins = list( p(NW, W, SW), p(N, C, S), p(NE, E, SE), p(NW, N, NE), p(W, C, E), p(SW, S, SE), p(NW, C, SE), p(SW, C, NE) ) final boolean isWin = wins.exists(new F<P3<Position, Position, Position>, Boolean>() { public Boolean f(final P3<Position, Position, Position> abc) { return list(abc._1(), abc._2(), abc._3()).mapMOption(mm.get()).exists(new F<List<Player>, Boolean>() { public Boolean f(final List<Player> ps) { return ps.allEqual(Equal.<Player> anyEqual()) } }) } }) final boolean isDraw = Position.positions().forall(new F<Position, Boolean>() { Boolean f(final Position pos2) { mm.contains(pos2) } }) j.isSome() ? MoveResult.positionAlreadyOccupied() : isWin ? MoveResult.gameOver(new FinishedBoard(bb, GameResult.win(wt))) : isDraw ? MoveResult.gameOver(new FinishedBoard(bb, Draw)) : MoveResult.keepPlaying(bb) } // … // … @Override String toString() { toString(new F2<Option<Player>, Position, Character>() { Character f(final Option<Player> pl, final Position _) { pl.option(p(' '), toSymbol) } }) + "n[ " + whoseTurn().toString() + " to move ]" } static final class EmptyBoard extends BoardLike { private EmptyBoard() {} @SuppressWarnings("unchecked") Board moveTo(final Position pos) { new Board(list(p(pos, Player1)), TreeMap.<Position, Player> empty(positionOrder).set(pos, Player1)) } private static final EmptyBoard e = new EmptyBoard() static EmptyBoard empty() { e } Player whoseTurn() { Player1 } boolean isEmpty() { true } List<Position> occupiedPositions() { nil() } int nmoves() { 0 } Option<Player> playerAt(Position pos) { none() } } static final class FinishedBoard extends BoardLike { private final Board b private final GameResult r private FinishedBoard(final Board b, final GameResult r) { this.b = b this.r = r } Board takeBack() { b.takeBack().fold( Bottom.<Board> error_("Broken invariant: board in-play with empty move list. This is a program bug"), Function.<Board> identity() ) } Player whoseTurn() { b.whoseTurn() } boolean isEmpty() { false } List<Position> occupiedPositions() { b.occupiedPositions() } int nmoves() { b.nmoves() } Option<Player> playerAt(final Position pos) { b.playerAt(pos) } GameResult result() { r } @Override String toString() { b.toString() + "n[[" + r.toString() + " ]]" } } }
  • 33. …Typing import groovy.transform.TypeChecked import tictactoe.* Import static tictactoe.Position.* @TypeChecked(visitor=TicTacToeTypeVisitor) void main() { Board.empty().move(NW).move(C).move(W).move(SW).move(SE) } package tictactoe enum Position { NW, N, NE, W, C, E, SW, S, SE } [Static type checking] - Attempt to call suboptimal move SE not allowed [HINT: try NE] Custom type checker which fails compilation if programmer attempts to code a suboptimal solution. Where suboptimal means doesn’t agree with what is returned by a minimax, alpha-beta pruning, iterative deepening solving engine.
  • 34. Show me the code