从列表列表到数据记录列表

Mit*_*ops 0 haskell

我正在解析一个看起来像这样的文件:

Good
id123
^
Bad
id456
^
Middle
id789
Run Code Online (Sandbox Code Playgroud)

记录由分隔^\n,该记录中的字段仅由分隔newlines

读取该文件并拆分后,最终得到的列表列表如下所示:

[["Good","id123",""],["Bad","id456",""],["Middle","id789",""]]
Run Code Online (Sandbox Code Playgroud)

但是,我无法将其转换为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
Run Code Online (Sandbox Code Playgroud)

产生

[["Good","id123",""],["Bad","id456",""],["Middle","id789",""]]
Run Code Online (Sandbox Code Playgroud)

如预期的那样。但是尝试将其下一步,并将其转换为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_
Run Code Online (Sandbox Code Playgroud)

我得到:

<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
Run Code Online (Sandbox Code Playgroud)

要么

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))’
Run Code Online (Sandbox Code Playgroud)

我想把它[[Text]]变成[Rec]什么?

Mit*_*ops 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
Run Code Online (Sandbox Code Playgroud)

产生:

Rec "Good" "id123" ""
Rec "Bad" "id456" ""
Rec "Middle" "id789" ""
Run Code Online (Sandbox Code Playgroud)

\anonymous函数可以取一个\[l,i,s,t]