2013-10-11 47 views
1

我了,我想通过我的客户名单迭代找到正确的客户,当我发现他们,我想要展示的任何非零INT的附加到他们。我不知道如何继续。我知道店里只有一个人的姓名记录。基本哈斯克尔:列表理解

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'] 

回答

2

您的回答非常接近。首先,您需要更新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,你不必更新所有功能,不依赖于该领域。

+1

一如既往的完美谢谢! – John

4

阅读错误信息非常有用!

test23.hs:10:9: 
    Couldn't match type `(Name, t0)' with `(Name, Int, Int)' 
    Expected type: Customer 
     Actual type: (Name, t0) 

你有

getName (a, b) = a 

,但被定义

type Customer = (Name,Int,Int) 

右边的功能看起来像

getName (a, _, _) = a 

后正确的,你可以看下meassage:

test23.hs:17:26: 
    Couldn't match type `[Int]' with `Int' 
    Expected type: Customer -> Int 
     Actual type: Customer -> [Int] 
    In the first argument of `map', namely `getNumbers' 
    ... 
    In an equation for `rental' 

但错误不在getNumbers,但在签名rental:: Shop-> Name -> [Int]。必须是:

rental:: Shop-> Name -> [[Int]] 
+0

谢谢,但真正的问题是租赁算法。我不知道如何在检查名称与输入相同的同时打印出非零元素。 – John