【发布时间】:2021-10-27 23:07:45
【问题描述】:
Haskell 粉丝大家好!
我所有的问题都与 -- OVERLOADED(?) FUNCTION -- 部分有关,为了完整起见,我包括了其余部分。
-
我想知道使用模式匹配来重载我的函数 order 是否有意义,就像我在下面的示例中所做的那样。
-
我还想知道 order 函数的第一个版本中调用函数“checkBalance balance”的第一个函数是否总是得到 executerd(因为我没有为它指定模式)或从不(因为所有的 Food 模式都包含在下面的函数中)。
在此先感谢初学者:)
-- TYPE DECLARATIONS --
data Spice = Regular | Medium | Hot
data Base = Noodles | Rice
data Meat = Duck | Chicken | Pork
data Sauce = Tomato | Meatballs | Carbonara
data Food = Indian Spice | Pasta Sauce | Chinese Base Meat
data DeliveryOption = Pickup | Delivery
data DeliveryTime = Immediate | Later
type CreditBalance = Int
data Order = O Food DeliveryOption CreditBalance
data OrderStatus = Success | Pending | Declined
-- OVERLOADED(?) FUNCTION --
order :: (Order, CreditBalance) -> OrderStatus
order (O {}, balance)
| not (checkBalance balance ) = Declined
| ...
order (O Indian {} _ _, _)
| ...
order (O Pasta {} _ _, _)
| ...
order (O Chinese {} _ _, _)
| ...
-- ANOTHER FUNCTION --
checkBalance :: CreditBalance -> Bool
checkBalance balance
| balance > 100 = True
| otherwise = False
【问题讨论】:
-
order没有过载。各个定义只是order x = case x of (O {}, balance) -> ...之类的语法糖。 -
所以我写的基本上是一个覆盖在语法糖中的 switch 语句?有没有更优雅的方式来将不同的订单与指定类型的食物进行分支?
标签: haskell pattern-matching overloading