是否可以将 Haskell 中的列表转换为其中元素的字符串?

Is it possible to turn a list in Haskell into a string of the elemnts within?

我有一个小电影"database",它只是一个列表,列表中的每个元素都是一个元组。

我想以易于阅读的格式以字符串形式显示列表,因此例如列表中的每个数据项应显示如下:

Casino Royale
Daniel Craig, Eva Green
2006
Garry, Dave

Titanic
Leonardo DiCaprio, Kate Winslet
1997
Zoe, Amy

这是我使用的代码:

type Title = String
type Actors = [String]
type Year = Int
type Fans = [String]
type Film = (Title, Actors, Year, Fans)
type Database = [Film]

testDatabase :: Database
testDatabase = [("Casino Royale", ["Daniel Craig", "Eva Green"], 2006,["Garry", "Dave"]),
                ("Titanic", ["Leonardo DiCaprio", "Kate Winslet"], 1997, ["Zoe", "Amy"]),
....
]

一种方法是为 Film 编写您自己的 Show 实例。但是你需要启用一些扩展:

{-#LANGUAGE TypeSynonymInstances#-}
{-#LANGUAGE FlexibleInstances#-}
{-#LANGUAGE OverlappingInstances#-}

然后你创建一个实例 Show:

instance Show Film where
    show (t,a,y,f) = t ++ "\n" ++ actors ++ "\n" ++ (show y) ++ "\n" ++ fans
        where actors = intercalate ", " a
              fans = intercalate ", "  f

ghci 中的演示:

λ> mapM_ (\x -> (putStrLn $ show x) >> putStrLn "") testDatabase
Casino Royale
Daniel Craig, Eva Green
2006
Garry, Dave

Titanic
Leonardo DiCaprio, Kate Winslet
1997
Zoe, Amy

我建议您将 (a,b,c,d) 类型分解为记录数据结构。那更可取。

我能够通过在原始 post 的评论中使用@karakfa 的方法来产生我想要的结果:

pp :: Film -> String; pp (t,a,y,f) = i "\n" [t, i ", " a, show y, i ", " f] where i x = intercalate x