【发布时间】:2012-03-04 17:05:10
【问题描述】:
让两种变体类型:
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
我该如何处理?
【问题讨论】:
-
“因为它们的类型不同,我需要多态变体”——不。如果您向我们提供您正在使用的真实材料,我们能够更好地为您提供帮助,但您似乎在这里为自己创造了更多的工作。
标签: list functional-programming ocaml variant polymorphism