首页 > 解决方案 > 在 OCaml 中同时使用 List.exists、List.for_all 和 List.filter

问题描述

我正在尝试通过这些类型中列表的内容过滤用户定义类型的列表,我想知道是否有一种方法可以使用List.filter,List.existsList.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]

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

谢谢!

标签: ocamlhigher-order-functions

解决方案


您可以对应用于过滤器的函数进行模式匹配。要查找所有非黑色或体重 < 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 )


推荐阅读