我有一行簡單的文本文件:從文件哈斯克爾讀整數到列表
6 195 265 750 265 750 196
我有一個函數:
executeList :: Integer -> [Integer] -> [String]
executeList n x = [reverseAndAdd n i | i <- x]
這需要一個整數,整數的列表,返回一個字符串數組。
我想要做的是將該文本文件讀取到[Integer]列表並將其傳遞給executeList函數。 這裏是我的代碼:
main = do
let list = []
handle <- openFile "data.txt" ReadMode
contents <- hGetContents handle
let singlewords = words contents
list = f singlewords
print list
hClose handle
f :: [String] -> [Integer]
f = map read
我在這裏找到: Haskell file reading
當我運行 '主' 我得到這樣的輸出: [6,195,265,750,265,750,196]
但是當我嘗試將它傳遞像這樣執行清單:
let list = main
executeList 0 list
我得到這個錯誤:
<interactive>:103:15: error:
* Couldn't match expected type `[Integer]' with actual type `IO()'
* In the second argument of `executeList', namely `list'
In the expression: executeList 0 list
In an equation for `it': it = executeList 0 list
如果我檢查列表的類型,我得到這個:
list :: IO()
我擡頭一看互聯網如何把IO()爲[整數]上,但發現沒有什麼用處。也許有人可以告訴我做這種轉換的方式嗎?
而不是'print list',在你的main中使用'print(executeList 0 list)'?請注意,沒有(安全)功能'IO a - > a'。 – Zeta
謝謝!還有一個問題。是否有可能將此列表寫入同一函數中的某個其他文件?我嘗試添加如下內容: outh < - openFile「results.txt」WriteMode hPrint outh(executeList 0 list) hClose outh – motleycrue
但get:解析錯誤輸入'< - '。也許這個狀態應該是一個'做'塊? 錯誤。 – motleycrue