【翻訳】関数型プログラミング入門 | POSTD の「パイプラインを使う」をSwiftで書いてみた。
Last active
August 29, 2015 14:16
-
-
Save norio-nomura/090e0085a61ca2693e93 to your computer and use it in GitHub Desktop.
「【翻訳】関数型プログラミング入門 | POSTD」の「パイプラインを使う」をSwiftで書いてみた。
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
import Foundation | |
typealias Band = [String:String] | |
func assoc(var d: Band, key: String, value: String?) -> Band { | |
d[key] = value | |
return d | |
} | |
typealias FuncForBand = Band -> Band | |
func pipeline_each(bands: [Band], fns: [FuncForBand]) -> [Band] { | |
return reduce(fns, bands, map) | |
} | |
typealias StringConverter = String -> String | |
func call(key: String, fn: StringConverter)(band: Band) -> Band { | |
if let value = band[key] { | |
return assoc(band, key, fn(value)) | |
} else { | |
return band | |
} | |
} | |
func pluck(keys: [String])(band: Band) -> Band { | |
return reduce(keys, Band()) { | |
assoc($0, $1, band[$1]) | |
} | |
} | |
// FuncForBand | |
let strip_punctuation_from_name = call("name") { $0.stringByReplacingOccurrencesOfString(".", withString: "") } | |
let capitalize_names = call("name") { $0.capitalizedString } | |
let set_canada_as_country = call("country", {_ in return "Canada"}) | |
let extract_name_and_country = pluck(["name", "country"]) | |
// pipeline | |
var bands: [Band] = [ | |
["name": "sunset rubdown", "country": "UK", "active": "false"], | |
["name": "women", "country": "Germany", "active": "false"], | |
["name": "a silver mt. zion", "country": "Spain", "active": "true"] | |
] | |
pipeline_each(bands, [ | |
set_canada_as_country, | |
strip_punctuation_from_name, | |
capitalize_names, | |
extract_name_and_country, | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
call()
とpluck()
をCurried Functionに書き直した。