Haskell - 格式列表输出

时间:2012-04-16 19:34:23

标签: list haskell

testDatabase :: [Film]
testDatabase = [("Director 1","Film 1",2012,[]),("Director 2","Film 2",2,[])]

filmsByDirector :: String -> [Film]
filmsByDirector name = filter (\(a,_,_,_) -> a == name) testDatabase

我从另一个函数调用它,我正在尝试格式化列表,所以我可以看到如下输出:

Director: Director 1
Film Name: Film 1
Year: 2012
Ratings:

任何帮助?

1 个答案:

答案 0 :(得分:1)

您需要一个接受字符串并将其转换为格式化字符串的函数。实现是直接格式化。

formatString :: Film -> String

然后,您只需要将此函数应用于您感兴趣的每个Film(通过map)并加入(concat)最终字符串以获得结果。

type Film = (String, String, Int, [Int])

testDatabase :: [Film]
testDatabase = [("Director 1","Film 1",2012,[]),("Director 2","Film 2",2,[])]

filmsByDirector :: String -> [Film]
filmsByDirector name = filter (\(a,_,_,_) -> a == name) testDatabase

formatString :: Film -> String
formatString (dir, film, year, rat) = "Director: " ++ (show dir) ++ "\nFilm Name: " ++ (show film) ++ "\nYear:" ++ (show year) ++ "\nRatings: " ++ concatMap (\r -> (show r) ++ " ") rat

formattedByDirector :: String -> String
formattedByDirector dir = concatMap formatString $ filmsByDirector dir

putStrLn $ formattedByDirector "Director 1"