Last active
December 16, 2015 21:08
-
-
Save grimrose/5497032 to your computer and use it in GitHub Desktop.
Java 8を関数型っぽく使うためのおまじないをGroovyでやってみた
This file contains hidden or 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
/* | |
* http://d.hatena.ne.jp/nowokay/20130501#1367357873 | |
* 上記の記事をGroovyでやってみました。 | |
*/ | |
def enclose = { s -> "[" + s + "]" } | |
assert "[foo]" == enclose.call("foo") | |
assert "[foo]" == enclose("foo") | |
def capitalize = { s -> | |
s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase() | |
} | |
assert "Foo" == capitalize("foo") | |
assert "[Foo]" == enclose(capitalize("foo")) | |
assert "[Foo]" == (capitalize >> enclose)("foo") | |
def capEnc = capitalize >> enclose | |
assert "[Foo]" == capEnc("foo") | |
/* 関数合成 */ | |
def middle = { s -> s.substring(s.length().intdiv(3), (s.length() * 2).intdiv(3)) } | |
assert "[Foo]" == (middle >> capitalize >> enclose)("yoofoobar") | |
assert "[Foo]" == enclose(capitalize(middle("yoofoobar"))) | |
/* カリー化 */ | |
/* | |
* カリー化 != 部分適用 | |
* http://d.hatena.ne.jp/kmizushima/20091216/1260969166 | |
* を参考にさせていただきました。 | |
*/ | |
// 2 parameters | |
def sandwich = { enc -> { str -> enc + str + enc } } | |
assert "***sanded!***" == sandwich("***")("sanded!") | |
// 3 parameters | |
def encloseC = { pre -> { post -> { s -> pre + s + post } } } | |
assert "{enclosed!}" == encloseC("{")("}")("enclosed!") | |
// 部分適用 | |
def encloseCurly = encloseC("{")("}") | |
assert "{囲まれた!}" == encloseCurly("囲まれた!") | |
// Closure#curry | |
def encloseForGroovy = { pre, post, s -> pre + s + post } | |
def encloseForGroovyCurry = encloseForGroovy.curry("{").curry("}") | |
assert "{囲まれた!}" == encloseForGroovyCurry("囲まれた!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
rightShiftのところは素直に>>を使って書いた方が関数型っぽいんじゃないかと