让两人变量类型:如何处理多态变体列表?
type typeA =
| A1
| A2
;;
type typeB =
| B1 of typeA
| B2 of typeA
;;
和类型检查功能:
let isA1 = function A1 -> true | _ -> false;;
let isA2 = function A2 -> true | _ -> false;;
let isB1 = function B1 e -> true | _ -> false;;
let isB2 = function B2 e -> true | _ -> false;;
我想创建的那些功能的列表来检查A型或B
的元素因为它们是不同类型的,所以我需要多态变体,并且我得到:
type filterA =
{
handleA : typeA -> bool;
};;
type filterB =
{
handleB : typeB -> bool;
};;
type filterslist = [`FilterA of filterA | `FilterB of filterB] list ;;
let filters1 = [`FilterA { handleA = isA1 }; `FilterB { handleB = isB1 }] ;;
所以现在我要遍历filters1检查参数 我试过的类型:
let exec_filters filters event = List.iter (fun fil -> match fil with `FilterA -> fil.handleA event;()| `FilterB -> fil.handleB event;()) filters;;
,但它不是赞赏:
Error: This expression has type [< `FilterA | `FilterB ]
but an expression was expected of type filterA
我该如何处理呢?
“因为它们是不同类型的,我需要多态变体” - 不。如果你给我们提供与你合作的真实东西,我们可以更好地帮助你,但看起来你正在为自己创造更多的工作。 – Ashe 2012-03-05 01:43:19