Skip to content

Instantly share code, notes, and snippets.

@irof
Created June 30, 2011 16:03
Show Gist options
  • Save irof/1056546 to your computer and use it in GitHub Desktop.
Save irof/1056546 to your computer and use it in GitHub Desktop.
//break条件を受け取る感じで
class BreakException extends Exception {}
Object.metaClass.doBreak = { cond ->
if (cond()){
println 'break!'
throw new BreakException()
}
}
Object.metaClass.doloop = { proc ->
[ // whileの実装
'while': { cond ->
try {
proc()
while(cond()) {
proc()
}
} catch(BreakException ignore) {
}
},
// untilの実装
'until': { cond ->
try {
proc()
while(!cond()) {
proc()
}
} catch(BreakException ignore) {
}
}
]
}
// 以下、デモ
def a = 1
doloop {
println "[in do-while loop] $a"
a++
doBreak {a == 5}
}.while{ a < 10 }
doloop {
println "[in do-until loop] $a"
a++
doBreak {a == 10}
}.until{ a == 20 }
// こちらは以前試していた失敗作
class DoWhile {
def proc
def _do(Closure proc) {
this.proc = proc
return this
}
def _while(Closure cond) {
10.times {
println cond()
this.proc()
}
}
}
def dw = new DoWhile()
int i = 0
dw._do {
println "hello ${++i}"
}._while {
i < 50
}
// => java.lang.VerifyError: (class: ConsoleScript46$_run_closure2, method: doCall signature: (Ljava/lang/Object;)Ljava/lang/Object;) Expecting to find integer on stack
// at ConsoleScript46.run(ConsoleScript46:17)
// at groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:266)
// at groovy.lang.GroovyShell.run(GroovyShell.java:517)
// at groovy.lang.GroovyShell.run(GroovyShell.java:172)
// at groovy.lang.GroovyShell$run.call(Unknown Source)
// at groovy.ui.Console$_runScriptImpl_closure16.doCall(Console.groovy:910)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment