Haskell语言读取文件

问题描述 投票:0回答:1

我有txt 客户信息中有= [客户{customerId = 1,firstName =“Charlotte”,lastName =“White”,年龄= 56,电子邮件=“[电子邮件受保护]”,余额= 5645.416,riskNote =“中”} ,客户 {customerId = 2,firstName =“Alexander”,lastName =“Miller”,年龄 = 19,电子邮件 =“[电子邮件受保护]”,余额 = 9595.98,riskNote =“低”} ,客户 {customerId = 3,firstName =“John”,lastName =“Moore”,年龄 = 31,电子邮件 =“[电子邮件受保护]”,余额 = 2777.1067,riskNote =“低”} ]

和 我的 haskell 文件

import System.IO
import Text.Read (readMaybe)
import Data.List.Split (splitOn)


data Customer = Customer { customerId :: Int
                         , firstName :: String
                         , lastName :: String
                         , age :: Int
                         , email :: String
                         , balance :: Float
                         , riskNote :: String
                         } deriving (Show)



main :: IO ()
main = do
    handle <- openFile "customer.txt" ReadMode
    contents <- hGetContents handle

    let dosyaIcerigi = lines contents
   
    -- Customer'ları yazdır
    mapM_ print dosyaIcerigi

我可以打印这段文字。我可以将它分配给一个变量并逐行打印它。但是,我无法创建客户数据类型的列表。我可以在 Haskell 中执行此操作,但当我从文本文件中读取时则不能。你能帮我解决这个问题吗?

haskell haskell-stack haskell-lens template-haskell quest
1个回答
0
投票

让你的

Customer
也源自
Read

data Customer = Customer
  { customerId :: Int,
    firstName :: String,
    lastName :: String,
    age :: Int,
    email :: String,
    balance :: Float,
    riskNote :: String
  }
  deriving (Read, Show)

然后以

Customer
列表形式阅读内容,其中
read
:

main :: IO ()
main = do
  handle <- openFile "customer.txt" ReadMode
  contents <- hGetContents handle
  let dosyaIcerigi = read contents :: [Customer]
  -- Customer'ları yazdır
  mapM_ print dosyaIcerigi

话虽如此,通常您使用

show
read
进行序列化和反序列化:您使用JSON或CSV等格式,然后使用库在
Customer
之间进行转换。这也使得处理解析错误变得更加容易。

© www.soinside.com 2019 - 2024. All rights reserved.