Skip to content

Commit

Permalink
Update the parser combinator examples to reflect new either API.
Browse files Browse the repository at this point in the history
  • Loading branch information
beark committed Feb 2, 2014
1 parent a57fa54 commit e346f26
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 22 deletions.
29 changes: 10 additions & 19 deletions examples/parser_combinator/parser_combinator.cpp
@@ -1,6 +1,8 @@
#include "parser_combinator.h"
#include <sstream>

using namespace ftl;

parser<char> anyChar() {
return parser<char>([](std::istream& s) {
char ch;
Expand Down Expand Up @@ -66,32 +68,21 @@ parser<std::string> many(parser<char> p) {
return parser<std::string>([p](std::istream& s) {
auto r = (*p)(s);
std::ostringstream oss;
while(r) {
oss << *r;
while(r.template is<Right<char>>()) {
oss << *get<Right<char>>(r);
r = (*p)(s);
}

return yield(oss.str());
});
}

parser<std::string> many1(parser<char> p) {
using ftl::operator>>=;
std::string prepend(char c, std::string s) {
s.insert(s.begin(), c);
return s;
}

// Run p once normally, bind with what's essentially "many"
return p >>= [p](char t) {
return parser<std::string>([p,t](std::istream& strm) {
auto r = (*many(p))(strm);
if(r) {
r->insert(r->begin(), t);
return r;
}
else {
std::string s;
s.insert(s.begin(), t);
return yield(s);
}
});
};
parser<std::string> many1(parser<char> p) {
return curry(prepend) % p * many(p);
}

6 changes: 3 additions & 3 deletions examples/parser_combinatorics.cpp
Expand Up @@ -54,15 +54,15 @@ int main(int, char**) {
auto parser = parseLispList();
auto res = run(parser, std::cin);

while(!res) {
std::cout << "expected " << res.left().message() << std::endl;
while(res.isTypeAt<0>()) {
std::cout << "expected " << ftl::get<0>(res)->message() << std::endl;

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

res = run(parser, std::cin);
}

for(auto e : *res) {
for(auto e : *ftl::get<1>(res)) {
std::cout << e << ", ";
}

Expand Down

0 comments on commit e346f26

Please sign in to comment.