如何将FParsec结果值提取到FSI中的变量

时间:2016-03-28 14:58:52

标签: f# algebraic-data-types fparsec

我正在使用FParsec并尝试将结果值绑定到FSI中的变量。我尝试了以下内容:

        > run pint32 "3";; // succeeds
        val it : ParserResult<int32,unit> = Success: 3
        > let x = run pint32 "3";; 
        val x : ParserResult<int32,unit> = Success: 3
        > x;;  // I bind the result to x
        val it : ParserResult<int32,unit> = Success: 3
        > let Success(y, _, _) = x;;  //It looks like I can extract the value...
        val Success : y:'a * 'b * 'c -> ParserResult<int32,unit>
        > y;;
        ...error FS0039: The value or constructor 'y' is not defined

似乎绑定然后忘记它,但我认为我错过了一些东西,因为以下的解构工作:

> type AB = A of int | B
let aa = A 1
let A a = aa;;

type AB =
  | A of int
  | B
val aa : AB = A 1
val A : a:'a -> AB
> a;;
val it : int = 1

以下函数似乎能够使用匹配语句提取值(尽管我需要根据解析器更改失败类型):

> let extract p str =
        match run p str with
        | Success(result, _, _)   -> result
        | Failure(errorMsg, _, _) -> 3
let z = extract pint32 "3"
z;;

val extract : p:Parser<int,unit> -> str:string -> int
val z : int = 3
val it : int = 3

我误解了什么?

1 个答案:

答案 0 :(得分:5)

您遇到的问题与最近的问题相同:

F#: Destructuring bind with a discriminated union

您的let Success(y, _, _) = x行实际上正在创建一个名为Success的函数,该函数将一个3元组作为参数。您需要做的是let (Success(y, _, _)) = x