再说一次,我试图遍历客户列表以找到正确的客户,当我找到他们时,我想显示附加到他们的任何非零整数。我不确定如何进行。我知道商店里只会记录1个人的名字。
type Name = String
type Customer = (Name,Int,Int)
type Shop = [Customer]
shop = [cust1, cust2]
cust1 = ("Steve", 321, 123) :: Customer
cust2 = ("John", 0,678) :: Customer
getName :: Customer -> Name
getName (a, b,c) = a
getNumbers :: Customer -> [Int]
getNumbers (a,b,c) = filter (/=0) [b,c]
rental:: Shop-> Name -> [Int]
rental shop' name' = map getNumbers [ x|x<-shop',getName x == name']
您的答案非常接近。首先,您需要更新getName
为3个元组,其次,您应该使用concatMap getNumbers
而不是map getNumbers
。
虽然,看起来您将要向Customer
类型中添加新字段,所以我建议您改用记录:
data Customer = Customer
{ custName :: Name
, custVal1 :: Int -- I don't know what these are, so use real names
, custVal2 :: Int
} deriving (Eq, Show)
现在你可以摆脱getName
并做
getNumbers :: Customer -> [Int]
getNumbers c = filter (/= 0) [custVal1 c, custVal2 c]
rental :: Shop -> Name -> [Int]
rental shop' name' = concatMap getNumbers [x | x <- shop', custName x == name']
现在,如果要向中添加另一个字段Customer
,则不必更新不依赖于该字段的所有函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句