Skip to content

Instantly share code, notes, and snippets.

@norio-nomura
Last active August 29, 2015 14:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save norio-nomura/090e0085a61ca2693e93 to your computer and use it in GitHub Desktop.
Save norio-nomura/090e0085a61ca2693e93 to your computer and use it in GitHub Desktop.
「【翻訳】関数型プログラミング入門 | POSTD」の「パイプラインを使う」をSwiftで書いてみた。
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,
])
@norio-nomura
Copy link
Author

call()pluck()をCurried Functionに書き直した。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment