How to define <*> for applicative parser?

2019-08-12 21:18发布

问题:

Suppose we define parser as a function

type Parser[A] = String => List(A, String) 

The parser takes an input string and yields a sequence of pairs. Each pair consists of the parsing result and unconsumed part of the input

As I understand, we can define the parser as an applicative and implement a seq parser combinator in terms of <*>.

The seq combinator is a function, which takes two parsers p and q as its arguments and returns a new parser, which applies p and q to the input sequentially. For example:

val pa  = symbol('a') // parser, which recognizes 'a' as the 1st char in the input
val pb  = symbol('b') // parser, which recognizes 'b' as the 1st char in the input  
val pab = seq(pa, pb) // recognizes "ab"

Obviously, we can easily define flatMap for the parser and then define <*> in terms of that flatMap. Can we define <*> differently and implement seq with that <*> ?