因此,这是一周中每天的用户定义数据类型日(即:星期日,星期一等)
let is_weekend_day (d:day) : bool =
begin match d with
| Sunday -> true
| Saturday -> true
| _ -> false
end
有没有办法压缩代码?
ie: Sunday || Saturday -> true
the problem with this is that it's not in syntax, but having 2 additional
lines seems like such a waste of space!
答案 0 :(得分:5)
您可以使用|
组合模式,即or-pattern。
通过使用它并删除多余的类型注释并开始/结束,您将获得以下内容:
let is_weekend_day d =
match d with
| Sunday | Saturday -> true
| _ -> false
答案 1 :(得分:2)
你实际上可以这样写:
let is_weekend_day = function
| Sunday | Saturday -> true
| _ -> false
或者这个:
let is_weekend_day = ListLabels.mem ~set: [Saturday;Sunday];;
如果你想得到想象,你可以定义一个函数,将操作符从操作布尔值操作到操作返回布尔值的函数:
let lift op f g x = op (f x) (g x)
然后你可以像这样定义is_weekend_day:
let is_weekend_day = lift (||) ((=) Saturday) ((=) Sunday)
如果你将lift (||)
变成一个运算符,那就更好了:
let (|||) a b = lift (||) a b
let is_weekend_day = ((=) Saturday) ||| ((=) Sunday)
let is_mwf = ((=) Monday) ||| ((=) Wednesday) ||| ((=) Friday)
OCaml语法非常灵活。