我正在解析一个看起来像这样的文件:
Good
id123
^
Bad
id456
^
Middle
id789
记录由^\n
分隔,并且该记录中的字段
只需用newlines
分隔即可。
读取此文件并拆分后,我得到一个看起来像这样的列表列表:
[["Good","id123",""],["Bad","id456",""],["Middle","id789",""]]
但是,我无法将其转换为Rec类型列表。
这是我的代码:
{-# 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,使用:
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]
时我缺少什么?
答案 0 :(得分:5)
这有效:
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]
。