从列表列表到数据记录列表 [英] From a list of lists to a list of data records
本文介绍了从列表列表到数据记录列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在解析一个看起来像这样的文件:
I'm parsing a file that looks like this:
Good
id123
^
Bad
id456
^
Middle
id789
记录由 ^ \ n
分隔,并且该记录中的字段只需用换行符
分隔即可.
Records are separated by ^\n
, and fields within that record
are separated simply by newlines
.
读取此文件并拆分后,我得到一个看起来像这样的列表列表:
Reading this file and splitting, I end up with a list of lists that looks like this:
[["Good","id123",""],["Bad","id456",""],["Middle","id789",""]]
但是,我未能将其转换为Rec类型列表.
However, I fail to turn this into a list of Rec types.
这是我的代码:
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
import Data.Text as T
import Data.Text.IO as T
data Rec = Rec Text Text Text deriving Show -- simple
main :: IO ()
main = do
contents <- T.readFile "./dat.txf"
let seps = splitOn "^\n" contents
let recs = fmap (splitOn "\n") seps
print recs
main
生产
[["Good","id123",""],["Bad","id456",""],["Middle","id789",""]]
符合预期.但是尝试将其转到下一步,并将其转换为Recs,方法如下:
As expected. But trying to take this to the next step and turn these into Recs, with:
main_ :: IO ()
main_ = do
contents <- T.readFile "./dat.txf"
let seps = splitOn "^\n" contents
let recs = fmap (splitOn "\n") seps
print recs
print $ fmap (\(x, y, z) -> Rec x y z) recs
-- print $ fmap (\r -> Rec r) recs
-- let m = fmap (\x -> Rec [(x,x,x)]) recs
-- print m
-- print $ fmap (\x -> Rec t3 x) recs
-- where t3 [x,y,z] = (x,y,z)
main_
我得到:
<interactive>:7:44: error:
• Couldn't match type ‘[Text]’ with ‘(Text, Text, Text)’
Expected type: [(Text, Text, Text)]
Actual type: [[Text]]
• In the second argument of ‘fmap’, namely ‘recs’
In the second argument of ‘($)’, namely ‘fmap (\ (x, y, z) -> Rec x y z) recs’
In a stmt of a 'do' block: print $ fmap (\ (x, y, z) -> Rec x y z) recs
或
main__ :: IO ()
main__ = do
contents <- T.readFile "./dat.txf"
let seps = splitOn "^\n" contents
let recs = fmap (splitOn "\n") seps
print recs
print $ fmap (\x -> Rec (f x)) recs
where f [a,b,c] = (a,b,c)
main__
<interactive>:7:30: error:
• Couldn't match expected type ‘Text’ with actual type ‘(Text, Text, Text)’
• In the first argument of ‘Rec’, namely ‘(f x)’
In the expression: Rec (f x)
In the first argument of ‘fmap’, namely ‘(\ x -> Rec (f x))’
将 [[Text]]
转换为 [Rec]
时我缺少什么?
What am I missing to turn the [[Text]]
into [Rec]
?
推荐答案
这有效:
main :: IO ()
main = do
contents <- T.readFile "./dat.txf"
let seps = splitOn "^\n" contents
let recs = fmap (splitOn "\n") seps
-- print $ fmap (\[x, y, z] -> Rec x y z) recs
let tada = fmap (\[x, y, z] -> Rec x y z) recs
mapM_ print tada
main
产生:
Rec "Good" "id123" ""
Rec "Bad" "id456" ""
Rec "Middle" "id789" ""
\ anonymous
函数可以采用 \ [l,i,s,t]
.
这篇关于从列表列表到数据记录列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文