原理是模式匹配。换句话说,您可以执行以下操作:
orders stuff (Farm p1 p2 p3 feed) (cost1,cost2,cost3) =
case (p1, p2, p3) of
("Bert", "Donald", "Horace") -> {- something -}
("Bert", "Donald", "Sheila") -> {- something different -}
(_, "Abraham", _) -> {- when p2 is "Abraham" and the others can be anything -}
_ -> {- this is the default case -}
以不同的方式分配名称。如您所见,下划线可以匹配任何内容,并且有助于表明您已经处理了所有特殊情况,现在需要一些通用的东西。
如果你愿意,你可以使用可用的简写,因为函数参数也是模式——例如,你可以这样做:
orders stuff (Farm "Bert" "Donald" "Horace" feed) (cost1,cost2,cost3) = {- something -}
orders stuff (Farm "Bert" "Donald" "Sheila" feed) (cost1,cost2,cost3) = {- something different -}
orders stuff (Farm p1 "Abraham" p3 feed) (cost1,cost2,cost3) = {- when p2 is "Abraham" and the others can be anything -}
orders stuff (Farm p1 p2 p3 feed) (cost1,cost2,cost3) = {- this is the default case -}
但是,在这种情况下,我推荐使用case…of,因为它更易于阅读,而且当您想要更改参数中的某些内容时,您不必修改每个方程。