【问题标题】:How to extract an FParsec result value to a variable in FSI如何将 FParsec 结果值提取到 FSI 中的变量
【发布时间】:2016-07-15 20:46:01
【问题描述】:

我正在使用 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

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

> 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

我误会了什么?

【问题讨论】:

    标签: f# algebraic-data-types fparsec


    【解决方案1】:

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

    F#: Destructuring bind with a discriminated union

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 2016-11-21
      相关资源
      最近更新 更多