在 haskell 中使用 printf 打印数据库

print database with printf in haskel

我的 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]

问题是 castfansString 的列表,而不是 String 本身。 %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(至少第一个)。