ocaml - 在 OCaml 中同时使用 List.exists、List.for_all 和 List.filter
问题描述
我正在尝试通过这些类型中列表的内容过滤用户定义类型的列表,我想知道是否有一种方法可以使用List.filter
,List.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]
有没有办法只使用这些 List 函数来创建不是某种颜色的猫列表?这是一个家庭作业问题,所以我不能真正包含我的代码,但我添加了一个函数来隔离类型中的颜色列表,然后比较这些列表
谢谢!
解决方案
您可以对应用于过滤器的函数进行模式匹配。要查找所有非黑色或体重 < 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 )
推荐阅读
- google-cloud-platform - 我应该使用什么服务来处理 Cloud Storage 存储分区中的文件并上传结果?
- java - PostConstruct 不再可用
- c# - 在 C# 中合并两个 .CS 文件以生成新类
- sql-server - ssis 包没有在代理上安排作业执行
- javascript - js获取字母表中的字母个数
- spring - 是否可以从多个微服务(Spring Boot)生成一个war文件?
- c# - Tridion CoreService 中是否有获取页面取消发布信息的功能?
- laravel - 添加 Bootstrap 后未显示 Laravel Logout 下拉菜单
- php - Jquery 中的搜索区域,用于在来自另一个输入的输入网格中搜索
- java - 为什么一旦达到一定数量,进度就会减少?