[英]reading and writing to file in haskell
我正在嘗試讀取haskell中的文件。
最初我試過:
import System.IO
import Control.Monad
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] -> [Int]
f = map read
我已經更新了以下內容:
import System.IO
import Control.Monad
main = do
handle <- openFile "data.txt" ReadMode
contents <- hGetContents handle
print contents
但是,現在輸出看起來像:
"hdhdhdhhdhdhd\n"
"hdhdhdhdhh\n"
我希望輸出看起來像:
hdhdhhdhhdhdhdhd
hdhdhhshshshshshshh
您的第一個問題可以通過函數f = map read
來解釋。 此函數嘗試通過將各個字符串解析為整數值,將字符串列表轉換為整數列表。 由於您的文件包含hdhdhdhdhdhdhd\\nhdhdhdhdhdhh
,因此這些字符都不是偶數,並且您收到錯誤消息稱read
無法將它們解析為Int
。
第二個問題,一旦你刪除了解析階段以便只執行文件讀取就是你使用print
將文本輸出到屏幕,而這里使用的相應函數是putStr
或putStrLn
。 不同之處在於print
定義為print x = putStrLn (show x)
,因此在將值放入屏幕之前會自動將值轉換為字符串表示形式。 當你已經有一個String
,比如字符串x = "hello"
, show x
的輸出是"\\"hello\\""
,所以它包含引號和任何其他轉義字符。 這是read (show x) == x
,其中read
解析一個字符串,好像它是在源代碼中定義的,即在雙引號和適當的轉義字符之間。 因此,你只需要使用putStrLn
當你想打印一個String
到屏幕上,並print
,當您想將非字符串值打印到屏幕上,如Int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.