在 OCaml 中一起使用 List.exists、List.for_all 和 List.filter

Using List.exists, List.for_all, and List.filter together in OCaml

我正在尝试通过这些类型中列表的内容来过滤用户定义类型的列表,我想知道是否有办法使用 List.filterList.exists,和 List.for_all 来访问该内部列表,而不是创建一个函数来访问它。

type weight = int
type height = int 
type colours = Red | Black | Orange | White
type cat = Cat of weight * height * colours list

let cat1 = Cat (14, 14, [Red; Black])
let cat2 = Cat (15, 20, [Black; White])
let cat3 = Cat (13, 15, [Red; White])
let cats =  [cat1; cat2; cat3]

有没有一种方法可以仅使用这些列表函数来创建不是特定颜色的猫的列表?这是一个家庭作业问题,所以我不能真正包含我的代码,但我添加了一个函数来隔离类型中的颜色列表,然后比较这些列表

谢谢!

您可以模式匹配应用于过滤器的函数。要查找所有非黑色或体重 < 14 的猫,您可以使用:

utop # List.filter (function Cat (_,_,cat_colors) ->
                             List.for_all (fun x -> x != Black)
                             cat_colors ) cats ;;
- : cat list = [Cat (13, 15, [Red; White])]


utop # List.filter (function Cat (weight,_,_) -> weight < 14) cats ;;
- : cat list = [Cat (13, 15, [Red; White])]

其余的应该可以用两个应用程序 List.for_all(作为一个逻辑公式:∀c1:颜色∀c2:cat_cols。c1≠c2)。将鼠标悬停在扰流块上以显示完整的解决方案:

let choose colors = List.filter (function Cat (_,_,catcols) -> List.for_all (fun col -> List.for_all ((!=) col) catcols) colors )