讓兩人變量類型:如何處理多態變體列表?
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