我的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]
答案 0 :(得分:2)
问题是cast
和fans
是String
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
(至少第一个)。