使用FParsec解析int或float

lar*_*sjr 5 f# fparsec

我正在尝试使用FParsec解析文件,其中包含float或int值.我面临两个问题,我找不到一个好的解决方案.

1

双方pint32pfloat会成功解析相同的字符串,但给出不同的答案,比如pint32将返回3解析字符串时"3.0"pfloat返回3.0解析相同的字符串时.是否可以尝试使用解析浮点值pint32并使其失败如果字符串是"3.0"

换句话说,有没有办法使以下代码工作:

let parseFloatOrInt lines =
    let rec loop intvalues floatvalues lines =
        match lines with
        | [] -> floatvalues, intvalues
        | line::rest ->
            match run floatWs line with
            | Success (r, _, _) -> loop intvalues (r::floatvalues) rest
            | Failure _ -> 
                match run intWs line with
                | Success (r, _, _) -> loop (r::intvalues) floatvalues rest
                | Failure _ -> loop intvalues floatvalues rest

    loop [] [] lines
Run Code Online (Sandbox Code Playgroud)

这段代码将正确地将所有浮点值放在floatvalues列表中,但因为在解析字符串时pfloat返回,所有整数值也将放在列表中."3.0""3"floatvalues

2

上面的代码示例对我来说似乎有点笨拙,所以我猜测必须有更好的方法来做到这一点.我考虑过使用它们choice,但是两个解析器必须返回相同的类型才能工作.我想我可以使用一个float选项和一个int选项进行区分联合,并转换输出pint32pfloat使用|>>运算符.但是,我想知道是否有更好的解决方案?

byt*_*ter 3

考虑定义域数据并将解析器的定义及其在源数据上的使用分开,您走在正确的道路上。这似乎是一个很好的方法,因为随着您的现实项目进一步发展,您可能需要更多的数据类型。

我会这样写:

/// The resulting type, or DSL
type MyData =
    | IntValue of int
    | FloatValue of float
    | Error  // special case for all parse failures

// Then, let's define individual parsers:
let pMyInt =
    pint32
    |>> IntValue

// this is an alternative version of float parser.
// it ensures that the value has non-zero fractional part.
// caveat: the naive approach would treat values like 42.0 as integer
let pMyFloat =
    pfloat
    >>= (fun x -> if x % 1 = 0 then fail "Not a float" else preturn (FloatValue x))
let pError =
    // this parser must consume some input,
    // otherwise combined with `many` it would hang in a dead loop
    skipAnyChar
    >>. preturn Error

 // Now, the combined parser:
let pCombined =
    [ pMyFloat; pMyInt; pError ]    // note, future parsers will be added here;
                                    // mind the order as float supersedes the int,
                                    // and Error must be the last
    |> List.map (fun p -> p .>> ws) // I'm too lazy to add whitespase skipping
                                    // into each individual parser
    |> List.map attempt             // each parser is optional
    |> choice                       // on each iteration, one of the parsers must succeed
    |> many                         // a loop
Run Code Online (Sandbox Code Playgroud)

请注意,上面的代码能够处理任何源:字符串、流或其他任何源。您的真实应用程序可能需要使用文件,但单元测试可以通过仅使用string list.

// Now, applying the parser somewhere in the code:
let maybeParseResult =
    match run pCombined myStringData with
    | Success(result, _, _) -> Some result
    | Failure(_, _, _)      -> None // or anything that indicates general parse failure
Run Code Online (Sandbox Code Playgroud)

UPD。我已经根据评论编辑了代码。pMyFloat已更新以确保解析的值具有非零小数部分。