Haskell列出了列表的变量

时间:2017-12-29 16:06:19

标签: list haskell

假设我有数据

data Expense = MkExpense Double String deriving (Eq,Ord)

和一个功能

balanced :: [Expense] -> Double -> Bool
balanced expenses epsilon =
  let amounts = ...
  in maximum amounts - minimum amounts < epsilon;

计算费用清单是余额(即每个人因浮点错误而支付相同的最大epsilon差异),epsilon的值为0.01。

alogrithm是正确的,但是在三个点的位置,我想提取一个双打列表;即我参数中所有费用的两倍。如何在不更改数据类型的情况下执行此操作?

1 个答案:

答案 0 :(得分:2)

您可以按以下步骤操作:

balanced :: [Expense] -> Double -> Bool
balanced expenses epsilon =
  let amounts = map extractExpense expenses
  in maximum amounts - minimum amounts < epsilon

extractExpense将是您数据的Double值的解包器:

extractExpense :: Expense -> Double
extractExpense (MkExpense expense _) = expense

或者更简洁:

balanced :: [Expense] -> Double -> Bool
balanced expenses epsilon =
  let amounts = map extractExpense expenses
  in maximum amounts - minimum amounts < epsilon
    where extractExpense (MkExpense e _) = e