2013-10-11 46 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