[英]Reading from file and creating a data in haskell
我一直在嘗試讀取在 haskell 中創建數據的文件。 我構造了以下數據類型:
data Participant = Participant {name:: String, age:: Int,
country:: String, }
我擁有的文本文件是這種格式
Jack 21 England
Natalie 20 France
Sophie 24 France
每個單詞分別對應姓名年齡和國家。 我想閱讀文件並創建參與者列表。 但是 IO:String 似乎是脖子痛。 你有適合這個問題的孤子嗎?
IO 隔離不是缺陷,而是 Haskell 的一個特點,也是其明顯的成功之一。
如果您想將數據序列化到文件中,並將數據加載回您的程序中,您不必手動執行此操作。 使用任何序列化庫,其中有很多。 您還可以使用強大的 Aeson 庫,它可以轉換 JSON 中的數據並將它們加載回來。
如果您出於任何原因想要手動執行此操作,則必須首先定義自己的文件格式,並使其明確。 例如,如果 name 包含空格,您的示例會發生什么?
然后你應該定義一個 function 可以解析你的文件格式的一行並產生一個參與者readParticipant:: String -> Maybe Participant
。 注意可能,因為如果字符串格式錯誤,您的 function 將無法創建參與者,因此它將產生Nothing
。
然后你可以有一個 function 來解析參與者列表(注意復數) readParticipants:: String -> [Participants]
。 不可能在這里,因為列表本身允許失敗。
現在您可以擁有一個微型 IO function 來讀取文件內容,並在其上運行readParticipants
。
readParticipantsIO :: IO [Participants]
readParticipantsIO = readParticipants <$> readFile "participants.data"
-- alternative definition, exact same behaviour in this case
readParticipantsIO :: IO [Participants]
readParticipantsIO = do
content <- readFile "participants.data"
return $ readParticipants content
可以使用lines
和words
函數將字符串拆分為字符串列表,然后您可以 package 將這些字符串轉換為Participant
列表。
import Text.Read (readMaybe)
data Participant = Participant { name :: String, age :: Int, country :: String }
parseParticipants :: String -> [Participant]
parseParticipants fileContents = do
[name', age', country'] <- words <$> lines fileContents
Just age'' <- return (readMaybe age')
return (Participant { name = name', age = age'', country = country' })
main :: IO ()
main = do
participants <- parseParticipants <$> readFile "yourfile.txt"
-- do things with the participants
return ()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.