0

I'm trying to make a parser using Sprache I'm using F#. All the examples I've ever seen for the library use the Linq query syntax. I tried to translate the linq to f# using the "query" computation expression, but I got lost there.

Here is a sample I've been using.

[TestClass]
public class tests
{
    [TestMethod]
    public void test()
    {
        var input = "\"this is text\"";
        var content = Class1.Quoted.Parse(input);
        Assert.AreEqual("this is text", content);
    }
}
public class Class1
{
    public static readonly Parser<string> Quoted =
        (from open in Parse.Char('"')
         from content in Parse.CharExcept('"').Many().Text()
         from close in Parse.Char('"')
         select content);

    public static readonly Parser<string> Quoted2 =
        Parse.Char('"').SelectMany(open => 
        Parse.CharExcept('"').Many().Text(), ())
}

The obvious way to do it is to just translate the linq down to method calls, but I don't know how to do that. I tried looking at ILSpy, but that left me a bit confused.

How does the Linq query look as direct method calls?

phil
  • 1,416
  • 2
  • 13
  • 22
  • @Jashaszun I do. I'm not an expert, but I'm competent. What I don't know how to do is translate the linq query into method calls. I also don't know how to translate the linq query into an F# query thing. That's what I am asking in this question. – phil Jul 30 '15 at 17:16
  • @phil That makes sense. Sorry I seem insulting. – Jashaszun Jul 30 '15 at 17:19
  • @FrédéricHamidi true. I edited the question at the end. Is that better? – phil Jul 30 '15 at 17:19
  • @phil, okay, I probably misunderstood. Your question is all about LINQ method calls, not conversion to F#, right? If that's the case, you may want to reflect that in your title and make it more prominent in your question. – Frédéric Hamidi Jul 30 '15 at 17:20
  • Do you have Resharper? Resharper can convert between LINQ query syntax and method calls. – Jerry Federspiel Jul 30 '15 at 17:26
  • @JerryFederspiel I do not – phil Jul 30 '15 at 17:28

1 Answers1

0

Translating your example

(from open in Parse.Char('"')
from content in Parse.CharExcept('"').Many().Text()
from close in Parse.Char('"')
select content);

gives

(Parse.Char('"')
.SelectMany(open => Parse.CharExcept('"').Many().Text(), (open, content) => new {open, content})
.SelectMany(@t => Parse.Char('"'), (@t, close) => @t.content));

NB: Going to an approach more idiomatic to F# may be tricky because computation expressions don't seem to have an equivalent to the overload of SelectMany that C# LINQ syntax gets precompiled to (and that Sprache provides).

Jerry Federspiel
  • 1,504
  • 10
  • 14