Cam*_*ron 4 haskell functional-programming newline
我一直在浏览以前问过的问题,但找不到解决我问题的答案,尽管我认为至少有一个会解决。我只是想在函数内部的字符串之间添加换行符。每当我在字符串中添加“ \ n”时,它只会打印“ \ n”
import Data.List
-- aRow takes number of columns as argument
-- The idea is to use this function with the number of columns as argument.
-- Example, if we want 3 columns, we'd say aRow 3, and get "+---+---+---+"
aRow :: Int -> String
aRow n = "+" ++ take (4*n) (intercalate "" (repeat "---+")) ++ "\n|" ++ take (4*n) (intercalate "" (repeat " |"))
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出
"+---+---+---+---+\n| | | | |"
Run Code Online (Sandbox Code Playgroud)
我更喜欢
"+---+---+---+---+"
"| | | | |"
Run Code Online (Sandbox Code Playgroud)
行在单独的行上(竖线之间也应该有3个空格,请忽略我的格式。我主要是尝试使换行符起作用)。谢谢。
如果您仅在ghci中计算一个字符串表达式而不使用
putStr或putStrLn,它将只在其上调用show,因此该字符串"foo\n"将以"foo\n"ghci中的形式显示,但这并不会改变它是一个包含换行符的字符串并会打印的事实这样,一旦您使用进行输出putStr。
长话短说,您可能想要使用,putStr因为Haskell将默认使用show该字符串,并且将\n如此处为您所做的那样简单地显示。
例:
import Data.List
main = putStrLn(aRow 4)
aRow :: Int -> String
aRow n = "+" ++ take (4*n) (intercalate "" (repeat "---+")) ++ "\n|" ++ take (4*n) (intercalate "" (repeat " |"))
Run Code Online (Sandbox Code Playgroud)