Haskell: Scan Through a List and Apply A Different Function for Each Element

前端 未结 4 2008
我寻月下人不归
我寻月下人不归 2021-02-06 11:43

I need to scan through a document and accumulate the output of different functions for each string in the file. The function run on any given line of the file depends on what i

4条回答
  •  广开言路
    2021-02-06 11:56

    I show a solution for two types of line, but it is easily extended to five types of line by using a five-tuple instead of a two-tuple.

    import Data.Monoid
    
    eachLine :: B.ByteString -> ([Atom], [Sheet])
    eachLine bs | isAnAtom bs = ([ {- calculate an Atom -} ], [])
                | isASheet bs = ([], [ {- calculate a Sheet -} ])
                | otherwise = error "eachLine"
    
    allLines :: [B.ByteString] -> ([Atom], [Sheet])
    allLines bss = mconcat (map eachLine bss)
    

    The magic is done by mconcat from Data.Monoid (included with GHC).

    (On a point of style: personally I would define a Line type, a parseLine :: B.ByteString -> Line function and write eachLine bs = case parseLine bs of .... But this is peripheral to your question.)

提交回复
热议问题