[Haskell-cafe] minor refactoring problem
Martin DeMello
martindemello at gmail.com
Tue Nov 29 09:48:31 CET 2011
On Tue, Nov 29, 2011 at 12:35 AM, Stefan Holdermans
<stefan at vectorfabrics.com> wrote:
> Have you considered abstracting over the bits in which importFile and loadFile differ? For example:
>
> processFile :: (String -> IO [PairBox]) -> Editor -> String -> IO ()
> processFile f ed path = do
> s <- readFile path
> ps <- f s
> es <- return $ V.fromList ps
> writeIORef ed es
>
> importFile = processFile (mapM (\x -> makePair (x, "")) . lines)
> loadFile = processFile (mapM makePair . parseFile)
This was what I had tried; my issue was that the resulting code looked
harder rather than easier to read, so it felt more like golfing than
refactoring.
> Or, alternatively:
>
> processFile :: (String -> [a]) -> (a -> IO PairBox) -> Editor -> String -> IO ()
> processFile f g ed path = do
> s <- readFile path
> ps -> mapM g (f s)
> es -> return $ V.fromList ps
> writeIORef ed es
>
> importFile = processFile lines (\x -> makePair (x, ""))
> loadFile = processFile parseFile makePair
This does look significantly nicer - I hadn't thought of splitting it
into two functions rather than one, but it makes the code look much
less cluttered. (The trick with `flip` is tempting, but again at the
cost of having to peer rather too closely at the implementation of
processFile when reading the code). Thanks!
martin
More information about the Haskell-Cafe
mailing list