如何在保存结果的同时搜索元组并增加

时间:2014-07-20 13:53:10

标签: haskell

import Data.Char
import Data.List
import Data.Maybe

-- Sample test data
type Movies = (String, String)

sample :: [Movies]
sample = [("I am legend","Will Smith"),
        ("Rise of the Planet of the Apes","James Franco"),
        ("Godzilla","Bryan Cranston")]

sellTicket :: [Movies] -> String -> String -> [Movies]
sellTicket [] _ _ = []
sellTicket ((title, actor): xs) aTitle anActor
    | title == aTitle && actor == anActor = 
        (title, actor):sellTicket xs aTitle anActor
    | otherwise = (title,actor):sellTicket xs aTitle anActor

感谢各位帮忙,现在一切正常。

詹姆斯弗兰科正在猿人的星球上升。

1 个答案:

答案 0 :(得分:5)

试试这个:

sellTicket :: [Movies] -> String -> String -> [Movies]
sellTicket l title actor = sellTicketHelp l title actor False
  where      
    sellTicketHelp [] _ _ True = []
    sellTicketHelp [] title actor False = [(title, actor, 1)]
    sellTicketHelp ((t, a, q):xs) title actor b
        | title == t && actor == a = (t, a, q+1) : sellTicketHelp xs title actor True
        | otherwise = (t, a, q) : sellTicketHelp xs title actor b

sellTicket现在有一个辅助函数,除了其他参数之外还有一个布尔值,用于确定是否已找到匹配项。如果遍历了列表并且找到了匹配项,那么它确实返回空列表,其余的将被强制转换。否则,如果它还没有找到匹配,它将返回一个包含新电影的列表,其数量为1,所有内容都将被反馈回来。