SlideShare une entreprise Scribd logo
1  sur  35
Télécharger pour lire hors ligne
©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

Contenu connexe

Tendances

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 perspectiveNorman 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 explainedVaclav 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 GParsPaul King
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar 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 LaforgeGR8Conf
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in GroovyJim Driscoll
 
Grooscript gr8conf
Grooscript gr8confGrooscript gr8conf
Grooscript gr8confGR8Conf
 
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 2014Damien 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 ExamplesGanesh Samarthyam
 

Tendances (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
 

En vedette

Rhythm tic tac-toe
Rhythm tic tac-toeRhythm tic tac-toe
Rhythm tic tac-toedlynn525
 
Littlebits Tic Tac Toe
Littlebits Tic Tac ToeLittlebits Tic Tac Toe
Littlebits Tic Tac ToeJennifer Lewis
 
Tic Tac Presentation
Tic Tac PresentationTic Tac Presentation
Tic Tac Presentationgupsaurabh
 
TIC TAC TOE
TIC TAC TOETIC TAC TOE
TIC TAC TOEasmhemu
 
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 gameNadia Nahar
 

En vedette (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
 

Similaire à 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 LaneAndres Almiray
 
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 GoRodolfo Carvalho
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaRobot Media
 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in CodeEamonn Boyle
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume 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 Wsloffenauer
 
Cより速いRubyプログラム
Cより速いRubyプログラムCより速いRubyプログラム
Cより速いRubyプログラムkwatch
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov 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 GroovytestingAndres 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 2005Tugdual 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 GoMatt 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
 

Similaire à 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...
 

Plus de Paul King

groovy databases
groovy databasesgroovy databases
groovy databasesPaul King
 
Agile Testing Practices
Agile Testing PracticesAgile Testing Practices
Agile Testing PracticesPaul King
 
groovy DSLs from beginner to expert
groovy DSLs from beginner to expertgroovy DSLs from beginner to expert
groovy DSLs from beginner to expertPaul King
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrencyPaul King
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Dynamic Language Practices
Dynamic Language PracticesDynamic Language Practices
Dynamic Language PracticesPaul King
 
Make Your Builds More Groovy
Make Your Builds More GroovyMake Your Builds More Groovy
Make Your Builds More GroovyPaul King
 
Groovy Power Features
Groovy Power FeaturesGroovy Power Features
Groovy Power FeaturesPaul King
 
Make Your Testing Groovy
Make Your Testing GroovyMake Your Testing Groovy
Make Your Testing GroovyPaul King
 
Groovy Testing Sep2009
Groovy Testing Sep2009Groovy Testing Sep2009
Groovy Testing Sep2009Paul 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 TutorialPaul King
 
XML and Web Services with Groovy
XML and Web Services with GroovyXML and Web Services with Groovy
XML and Web Services with GroovyPaul King
 

Plus de 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
 

Dernier

Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 

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