Haskell new line not working

2019-03-02 13:02发布

Been messing around for about 20 minutes now trying to get the new line working however it always shows in GHCI as a single line.

Here is what I enter into GHCi:

displayFilm ("Skyfall",["Daniel Craig", "Judi Dench", "Ralph Fiennes"], 2012, ["Bill", "Olga", "Zoe", "Paula", "Megan", "Sam", "Wally"])

Here is what is printed:

"Skyfall----------\n Cast: Daniel Craig, Judi Dench, Ralph Fiennes\n Year: 2012\n Fans: 7\n"

displayList :: [String] -> String
displayList [] = ""
displayList [x] = x ++ "" ++  displayList []
displayList (x:xs) = x ++ ", " ++ displayList xs


displayFilm :: Film -> String
displayFilm (title, cast, year, fans) = 
    title ++ "----------" ++
    "\n Cast: " ++ (displayList cast) ++
    "\n Year: " ++ (show year) ++
    "\n Fans: " ++ show (length fans) ++ "\n"

2条回答
我命由我不由天
2楼-- · 2019-03-02 13:38

When you type an expression into GHC, it displays it using print. Calling print on a string shows its content but does not evaluate escape sequences:

> print "line1\nline"
"line1\nline2"

Note the quotes.

To actually print the string, use putStr or putStrLn (the latter will append a newline).

> putStr "line1\nline2"
line1
line2
查看更多
Root(大扎)
3楼-- · 2019-03-02 14:00

To print a string as it is, without escaping special characters, use:

putStr string

or

putStrLn string

if you want an extra newline at the end. In you case, you are probably looking for

putStr (displayFilm (....))

Why is this needed? In GHCi, if you evaluate an expression s the result will be printed as if running print s (unless it has type IO something -- forget about this special case). If e is a string, print escapes all the special characters and output the result. This is because print is meant to output a string whose syntax follows the one in Haskell expressions. For numbers, this is the usual decimal notation. For strings, we get quotes and escaped characters.

查看更多
登录 后发表回答