3

我希望有人可能会发布一个使用 FParsec 的示例,其中数据基于某种传入的实时流。

一些示例可能是基于鼠标手势生成结果,基于特定的股票报价序列生成警报或通知。

如果有人可以发布一个示例,将不胜感激。

谢谢!

4

1 回答 1

3

您正在寻找的是Rxx中的反应式解析器。

这不是 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()
于 2012-04-07T01:11:23.580 回答