在haskell中使用printf打印数据库

时间:2015-03-15 00:23:35

标签: haskell haskell-platform

我的printf方法有问题。我正在尝试打印testDatabase中的所有电影。是我在printf中使用的格式字符的问题吗?

import Prelude
import Data.Char
import Data.Int
import Text.Printf

    -- Types
type Title = String
type Actor = String
type Cast = [Actor]
type Year = Int
type Fan = String
type Fans = [Fan]
type Period = (Year, Year)
    type Database = [Film]

testDatabase :: Database
testDatabase = [("The Gunman", ["Idris Elba", "Sean Penn", " Javier Bardem"], 2015,["Garry", "Dave", "Zoe", "Kevin", "Emma"]),
                ("The Shawshank Redemption", ["Tim Robbins", "Morgan Freeman", "Bob Gunton"],1994, ["Bill", "Jo", "Garry", "Kevin", "Olga", "Liz"]),
                ("The Dark Knight", ["Christian Bale", "Heath Ledger","Aaron Eckhart"], 2008, ["Zoe","Heidi", "Jo", "Emma", "Liz", "Sam", "Olga", "Kevin", "Tim"]),
                ("Inception", ["Leonardo DiCaprio", "Ellen Page"], 2010, ["Jo", "Emma", "Zack", "Olga", "Kevin"])]



printFilms :: Database -> IO()
printFilms [] = putStrLn "There are no films in the database"
printFilms filmList = sequence_ [printf("|%-s| |%-20s| |%2d| |%.1f|\n") title cast year fans | (title, cast, year, fans) <- filmList]




 No instance for (IsChar [Char]) arising from a use of `printf'
Possible fix: add an instance declaration for (IsChar [Char])
In the expression:
  printf ("|%s| |%-20s| |%2d| |%.1f|") title cast year fans
In the first argument of `sequence_', namely
  `[printf ("|%s| |%-20s| |%2d| |%.1f|") title cast year fans |
      (title, cast, year, fans) <- filmList]'
In the expression:
  sequence_
    [printf ("|%s| |%-20s| |%2d| |%.1f|") title cast year fans |
       (title, cast, year, fans) <- filmList]

1 个答案:

答案 0 :(得分:2)

问题是castfansString s的列表,而不是String s本身。 %s仅支持单个字符串。 printf的内部类型魔术稍微混淆了错误消息,但基本上告诉它需要Char而不是String = [Char]

您需要将这些列表转换为您希望自己打印的方式。像

这样的东西
printFilms filmList = sequence_
    [printf("|%-s| |%-20s| |%2d| |%.1f|\n") title (unwords cast) year (unwords fans)
    | (title, cast, year, fans) <- filmList]

应该允许你编译它,尽管你可能想用你自己的子格式化函数替换unwords(至少第一个)。