-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathParserMonad.cs
More file actions
70 lines (60 loc) · 2.4 KB
/
ParserMonad.cs
File metadata and controls
70 lines (60 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
namespace ParserCombinators
{
public static class ParserMonad
{
public static Parser<TToken, TTree2> Select<TToken, TTree, TTree2>(
this Parser<TToken, TTree> parser,
Func<TTree, TTree2> selector)
{
return consList =>
{
var result = parser(consList);
if (result != null)
return new Result<TToken, TTree2>(selector(result.Tree), result.Rest);
else
return null;
};
}
public static Parser<TToken, TTree2> SelectMany<TToken, TTree, TIntermediate, TTree2>(
this Parser<TToken, TTree> parser,
Func<TTree, Parser<TToken, TIntermediate>> selector,
Func<TTree, TIntermediate, TTree2> projector)
{
return consList =>
{
var result = parser(consList);
if (result != null)
{
var result2 = selector(result.Tree)(result.Rest);
if (result2 != null)
return new Result<TToken, TTree2>(projector(result.Tree, result2.Tree), result2.Rest);
}
return null;
};
}
public static Parser<TToken, TTree> Where<TToken, TTree>(
this Parser<TToken, TTree> parser,
Func<TTree, bool> predicate)
{
return consList =>
{
var result = parser(consList);
if (result != null && predicate(result.Tree))
return result;
else
return null;
};
}
public static Parser<TToken, TTree2> Cast<TToken, TTree, TTree2>(this Parser<TToken, TTree> parser)
where TTree : TTree2
{
return parser.Select(tree => (TTree2)tree);
}
public static Parser<char, TTree2> Cast<TTree, TTree2>(this Parser<char, TTree> parser)
where TTree : TTree2
{
return parser.Select(tree => (TTree2)tree);
}
}
}