Given a Parser type as following:
public struct Parser<Result> {
internal let parse: (String) -> (Result, String)?
public func run(_ string: String) -> (Result, String)? {
guard let (result, remainder) = parse(string) else { return nil }
return (result, remainder)
}
public func map<T>(_ transform: @escaping (Result) -> T )
-> Parser<T> {
return Parser<T> { input in
guard let (result, remainder) = self.run(input) else { return nil }
return (transform(result), remainder)
}
}
public func followed<A>(by other: Parser<A>) -> Parser<(Result, A)> {
return Parser<(Result, A)> { input in
guard let (result, remainder) = self.run(input) else { return nil }
guard let (resultA, remainderA) = other.run(remainder) else { return nil }
return ((result, resultA), remainderA)
}
}
}
First implementation as following:
infix operator >>> : FunctionCompositionPrecedence
public func >>> <A, B> (lhs: Parser<A>, rhs: Parser<B>)
-> Parser<(A,B)> {
return lhs.followed(by: rhs)
}
Second implementation as following:
infix operator >>> : FunctionCompositionPrecedence
extension Parser {
public static func >>> <A, B> (lhs: Parser<A>, rhs: Parser<B>)
-> Parser<(A,B)> {
return lhs.followed(by: rhs)
}
}
Reclaim the question as what is the difference between the first implementation and the second one.
Moreover, when I use the first implementation, and compile the following code, the compiler reported an error as "'map' produces 'Parser', not the expected contextual result type 'Parser'"
extension Parser {
public static func apply <A, B> (_ lhs: Parser<(A)->B>, _ rhs: Parser<A>) -> Parser<B> {
return (lhs >>> rhs).map{(arg) -> B in let (f, x) = arg; return f(x)}
}
}
However, after I use the second implementation, everything goes fine. I am so confused about the essential nuances between them.