Batch modify files Haskell -
i trying create program adds simple text header every file in directory (and subdirectories). need using built in functions ghc (i can't access cabal).
the type signature of functions are
getrecursivecontents :: filepath -> io [filepath] addheadertofile :: string -> filepath -> io ()
these both work fine independently struggling use 2 functions in conjunction because of types. assumed using map correct way this, far have been unsuccessful.
addheadertomultiple :: string -> io [filepath] -> io () addheadertomultiple header files = map (addheadertofile header) files
i understand not work due types used have not found way fix it.
start running io action producing file list:
addheadertomultiple :: string -> io [filepath] -> io () addheadertomultiple header files = -- files has type io [filepath] paths <- files -- paths has type [filepath], can map on map (addheadertofile header) paths -- produces [io ()], not io ()
we hit problem in last line, builds list of io actions instead of running them. use helper function:
runinsequence :: [io ()] -> io () runinsequence [] = return () -- nothing runinsequence (a:as) = >> runinsequence
which can simplified to
runinsequence = foldr (>>) (return ())
actually, there exists library function doing that: it's called sequence_
. our code becomes
import control.monad addheadertomultiple header files = paths <- files sequence_ (map (addheadertofile header) paths) -- produces io (), it's ok
the combo sequence_ (map ...
has own library function well, called mapm_
:
addheadertomultiple header files = paths <- files mapm_ (addheadertofile header) paths
this can further refined using >>=
directly
addheadertomultiple header files = files >>= mapm_ (addheadertofile header)
Comments
Post a Comment