Created
April 8, 2011 12:31
-
-
Save fumokmm/909738 to your computer and use it in GitHub Desktop.
Groovyでdo-whileループ。http://d.hatena.ne.jp/fumokmm/20110630/1309446463
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Object.metaClass.doloop = { proc -> | |
[ // whileの実装 | |
'while': { cond -> | |
proc() | |
while(cond()) { | |
proc() | |
} | |
}, | |
// untilの実装 | |
'until': { cond -> | |
proc() | |
while(!cond()) { | |
proc() | |
} | |
} | |
] | |
} | |
// 以下、デモ | |
def a = 1 | |
doloop { | |
println "[in do-while loop] $a" | |
a++ | |
}.while{ a < 10 } | |
doloop { | |
println "[in do-until loop] $a" | |
a++ | |
}.until{ a == 20 } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// こちらは以前試していた失敗作 | |
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