type ColType = I of int | S of string | F of float
我知道您不能从模式匹配中返回其他类型,这就是为什么我首先为要创建的解析器创建此类型的原因。但是使用以下代码:
//create i coltype
let m (x : int) : ColType =
ColType.I x
//create f coltype
let n (x : float) : ColType =
ColType.F x
//create s coltype
let b (x : string) : ColType =
ColType.S x
let pColType =
let innerFn (charList : char list) =
let i = String(List.toArray charList)
match i with
| "int" -> m
| "float" -> n
| "string" -> b
many1 parseLowercase |>> innerFn
尽管m,n和b返回相同的类型,它仍然会给我pColType函数一个错误。
诸如parseLowercase等代码只是获取字符串的代码,这按预期运行,问题是尽管所有都是coltype的,返回值也不相同? (状态各不相同)。
答案 0 :(得分:1)
就像rmunn和Romanov提到的那样,您的3个函数的类型不同。您可以使用obj -> ColType
和box
使它们返回实例unbox
的单一类型:
let pColType =
let innerFn (charList : char list) =
let i = String(List.toArray charList)
match i with
| "int" -> unbox >> m
| "float" -> unbox >> n
| "string" -> unbox >> b
|_-> failwithf "error %A" i
many1 parseLowercase |>> innerFn
这要求您在调用结果函数之前先box
的值。
由于您正在构建解析器,因此使其返回string -> ColType
更为有意义:
let pColType =
let innerFn (charList : char list) =
let i = String(List.toArray charList)
match i with
| "int" -> parseInt >> m
| "float" -> parseFloat >> n
| "string" -> parseString >> b
|_-> failwithf "error %A" i
many1 parseLowercase |>> innerFn