如何处理多态变体列表?

cod*_*nk1 3 polymorphism ocaml functional-programming list variant

让两种变体类型:

type typeA = 
    | A1 
    | A2
;;  

type typeB = 
    | B1 of typeA
    | B2 of typeA
;;  
Run Code Online (Sandbox Code Playgroud)

和类型检查功能:

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;; 
Run Code Online (Sandbox Code Playgroud)

我想创建一个列表来检查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 }] ;;
Run Code Online (Sandbox Code Playgroud)

所以现在我想迭代filters1来检查我试过的参数的类型:

let exec_filters filters event = List.iter (fun fil -> match fil with `FilterA -> fil.handleA event; ()| `FilterB -> fil.handleB event; () ) filters;;
Run Code Online (Sandbox Code Playgroud)

但不赞赏:

Error: This expression has type [< `FilterA | `FilterB ]
       but an expression was expected of type filterA
Run Code Online (Sandbox Code Playgroud)

我怎么处理这个?

Kri*_*ski 5

你正在使用类似于Scheme或instanceOf的"类型检查谓词"这一事实表明你的代码可能存在一些问题.OCaml是一种静态类型语言,你不应该:

迭代filters1以检查我尝试的参数的类型

你为什么做这个?如果您尝试处理多种类型,那么执行此操作的方法是使用多态.多态变体可能对此有所帮助,但我仍然不相信你的代码不只是以一种奇怪的方式编写.