我希望有人可以发布使用FParsec的示例,其中数据基于某种传入的直播流。
一些示例可能是基于鼠标手势生成结果,根据特定的股票刻度序列生成警报或通知。
如果有人可以发布一个例子,我们将不胜感激。
谢谢!
答案 0 :(得分:3)
您正在寻找的是Rxx中的Reactive Parsers。
这不是F#,而是一个.NET库,让你编写代码,例如(从你的股票示例开始):
var alerts = ticks.Parse(parser =>
from next in parser
let ups = next.Where(tick => tick.Change > 0)
let downs = next.Where(tick => tick.Change < 0)
let downAlert = from manyUps in ups.AtLeast(2).ToList()
from reversalDown in downs.NonGreedy()
where reversalDown.Change <= -11
select new StockAlert(manyUps, reversalDown)
let upAlert = from manyDowns in downs.AtLeast(2).ToList()
from reversalUp in ups.NonGreedy()
where reversalUp.Change >= 21
select new StockAlert(manyDowns, reversalUp)
select downAlert.Or(upAlert).Ambiguous(untilCount: 1));
当然,还有Dave Sexton和James Miles,他们完成了大部分工作。
对于背景阅读,Rxx的解析器扩展来自于此讨论:http://qa.social.msdn.microsoft.com/Forums/eu/rx/thread/0f72e5c0-1476-4969-92da-633000346d0d
这是一个非常简单的例子,说明如何在F#中使用它:
open Rxx.Parsers.Reactive
open Rxx.Parsers.Reactive.Linq
// F# shortcuts to Rxx
let where f (a:IObservableParser<_,_>) = a.Where(fun b -> f b)
let toList (parser:IObservableParser<_,_>) = parser.ToList()
let (<&>) (a:IObservableParser<'a,'b>) (b:IObservableParser<'a,'b>) = a.And(b)
let create a =
{ new ObservableParser<_,_>() with
override x.Start = a(x.Next) } :> IObservableParser<_,_>
let parse (parser:IObservableParser<_,_>) (obs:IObservable<_>) = obs.Parse(parser)
// example of grammar
let grammar =
(fun (parser:IObservableParser<_,_>) ->
let next = parser.Next
let bigs = next |> where(fun i -> i > 25)
let smalls = next |> where(fun i -> i <= 25)
bigs <&> smalls |> toList )
|> create
// the test
let random = Random()
let values = Observable.Interval(TimeSpan.FromMilliseconds(500.0)).Select( fun _ -> random.Next(1,50)).Trace().TraceSubscriptions("subbing","subbed","disposing","disposed").Publish()
let sub = values |> parse grammar |> Observable.add(printfn "BIG THEN SMALL: %A")
let test = values.Connect()