From a list of lists to a list of data records

拈花ヽ惹草 提交于 2020-01-16 09:43:47

问题


I'm parsing a file that looks like this:

Good
id123
^
Bad
id456
^
Middle
id789

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",""]]

However, I fail to turn this into a list of Rec types.

Here's my code:

{-# 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

Produces

[["Good","id123",""],["Bad","id456",""],["Middle","id789",""]]

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_

I get:

<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

or

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))’

What am I missing to turn the [[Text]] into [Rec] ?


回答1:


This works:

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

Produces:

Rec "Good" "id123" ""
Rec "Bad" "id456" ""
Rec "Middle" "id789" ""

The \anonymous function can take a \[l,i,s,t].



来源:https://stackoverflow.com/questions/55643003/from-a-list-of-lists-to-a-list-of-data-records

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!