Skip to content

Instantly share code, notes, and snippets.

Created September 20, 2016 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/aa6133525e9e0190816ba8a1e911a6b5 to your computer and use it in GitHub Desktop.
Save anonymous/aa6133525e9e0190816ba8a1e911a6b5 to your computer and use it in GitHub Desktop.
Parsing Without Operators
import Foundation
typealias JSONKey = String
typealias JSONValue = AnyObject
typealias JSON = [JSONKey: JSONValue]
extension Optional {
func apply<T>(f: (Wrapped -> T)?) -> T? {
if let value = self, function = f {
return function(value)
} else {
return .None
}
}
}
extension Dictionary {
func extract<T>(key: Key) -> T? {
return transform(self[key])
}
}
func curry<A, B, C, R>(f: (A, B, C) -> R) -> A -> B -> C -> R {
return { a in
{ b in
{ c in
f(a, b, c)
}
}
}
}
func transform<T, R>(value: T) -> R? {
return value as? R
}
struct User {
let id: Int
let name: String
let email: String?
}
func map<A, B>(f: A -> B, _ a: A?) -> B? {
if let x = a {
return f(x)
} else {
return .None
}
}
func apply<A, B>(f: (A -> B)?, _ a: A?) -> B? {
if let x = a {
if let fx = f {
return fx(x)
}
}
return .None
}
let jsonOptional: NSDictionary? = ["id" : 1, "name" : "Vasia", "email" : "aaa@mail.com"]
let user = transform(jsonOptional).flatMap { (json: JSON) -> User? in
return json.extract("name")
.apply(json.extract("email")
.apply(json.extract("id")
.map(curry(User.init))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment