在Haskell中将复杂对象转换为字符串?

时间:2014-02-25 14:08:23

标签: string object haskell output

我目前正在编写一个程序,将多种自定义数据类型存储为"电影"类型。

type Director = String
type Title = String
type Year = Int
type Rating = (String, Int)
type Film = (Title, Director, Year, Rating)

createFilm :: Title -> Director -> Year -> Rating -> Film
createFilm w x y z = (w, x, y, z)

makeRating :: String -> Int -> Rating
makeRating x y = (x, y)

addToDatabase :: IO () 
addToDatabase = do
    putStr "Enter the title of the film: "
    title <- getLine
    putStr "Enter the director's name: "
    director <- getLine
    putStr "Enter the year the movie was released: "
    year <- getLine
    putStr "Please enter your name: "
    name <- getLine
    putStrLn "Please enter your rating: "
    rating <- getLine
    print (createFilm title director (read year) (makeRating name (read rating)))

最后打印的示例输出是("Test", "Test", 1900, ("Test", 5)) 如何将其转换为可以在以后写入文本文件的可用字符串?

例如,将此确切输出直接转换为"("Test", "Test", 1900, ("Test", 5))"

1 个答案:

答案 0 :(得分:2)

如果您只是想要"("Test", "Test", 1900, ("Test", 5))",那么show film会给您一个确切的信息。

但是,如果我可以提出建议,而不是使用类型同义词构造所有内容,请创建自己的类型。有很多好处,因为你不能混淆4元素元组代表什么,你可以提供更好的抽象。也许它现在不值得,但如果你要将它构建成更复杂的东西,那么正确的类型是必须的。

type Director = String
type Title = String
type Year = Int
data Rating = Rating {ratingName :: String, ratingScore :: Int}
data Film = Film { title    :: Title
                 , director :: Director
                 , year     :: Year
                 , rating   :: Rating}

现在,根据你想要的东西印刷方式,有一些选择。默认情况下,您可以为其中每个添加deriving Show,然后在获得Film值后,使用函数show获取字符串

"Film {title = \"Test\",
       director = \"Test\",
       year = 1990, 
       rating = Rating {ratingName = \"Test\", ratingScore = 5}}"

更漂亮,但如果你想要不同的东西,你可以添加一个

 instance Show Rating where
   show (Rating name value) = ...
 instance Show Film where
   show (Film title director year rating) = ...
       where ratingString = show rating

现在要获得漂亮的打印字符串,只需拨打show