2017-02-23 73 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功能,連接字符串列表,每個元素都以換行字符分隔。