2017-02-23 65 views
2

我是一个完整的新手哈斯克尔,并有以下问题: 我打算创建函数,它将三个字符串放在不同的行上。下面是代码:新行缩进哈斯克尔

onThreeLines :: String -> String -> String -> String 
onThreeLines a b c = a++"\n"++b++"\n"++c 

这里是我运行:

onThreeLines "Life" "is" "wonderful" 

而且我得到什么:

"Life\nis\nwonderful" 

我也曾尝试下面的字符,但它不工作也是如此。

"'\n'" 

回答

4

您的功能有效。如果您正在GHCi中运行此程序,或者使用print,则可能会因计算结果调用show这一事实而感到困惑,该算​​法将一个值设置为Haskell的调试术语。对于字符串,这意味着包括引号和转义。

putStrLn (onThreeLines "Life" "is" "wonderful")应该完全符合您的期望。

4

执行像这样应该使其工作:

main :: IO() 
main = putStrLn $ onThreeLines "hello" "world" "test" 

执行程序,我得到:

$ ./test.hs 
hello 
world 
test 

您得到"Life\nis\nwonderful"的原因是因为Show情况下正用于显示这将逃避换行。

λ> putStrLn "hello\nworld" 
hello 
world 
λ> print "hello\nworld" 
"hello\nworld" 

注意print使用Show实例展示。

2

你的功能没有问题。 “Life \ nis \ nwonderful”是你想要的结果字符串。只要记住,如果你想正确呈现新行,它传递给一个函数像putStrLn

putStrLn (onThreeLines "Life" "is" "wonderful") 

此外,一定要检查出unlines功能,连接字符串列表,每个元素都以换行字符分隔。