[Haskell-cafe] Is StateT what I need?

Andre Nathan andre at digirati.com.br
Tue Dec 18 13:47:26 EST 2007


Hello

On Mon, 2007-12-17 at 21:22 -0200, Andre Nathan wrote:
> Thanks everyone for the great suggestions. The code is much cleaner now
> (not to mention it works :)

I'm trying to finish the process tree construction but I guess I'll need
some help again.

My idea is to have a function that would return a map representing the
process tree

> createTree :: IO PsTree
> createTree = do
>   entries <- getDirectoryContents "/proc"
>   return $ foldr buildTree Map.empty entries

The "return $ foldr ..." part is missing something, because buildTree
would have be something like:

> buildTree :: String -> PsTree -> StateT PsMap IO PsTree
> buildTree entry tree = do
>   case matchRegex (mkRegex "^[0-9]+$") entry of
>     Nothing -> return tree -- skip this entry
>     Just _  -> do
>       psMap <- get
>       if Map.member dir psMap
>         then return tree -- alread inserted
>         else return $ insertInTree dir tree

so the types don't match. insertInTree would be something like (in
pseudo-code):

> insertInTree pid tree = do
>   procInfo <- insertProc pid -- this inserts pid in the state map
>                              -- and returns a PsInfo, so its type is
>                              -- Pid -> StateT PsMap IO PsInfo.
>                              -- Can I use it here though?
>   psMap <- get
>   if pid == "1" -- init is the root of the tree
>     then do modify (Map.insert "1" procInfo psMap)
>             return $ Map.insert "1" procInfo tree
>     else do
>       let pPid = parentPid procInfo
>       if Map.member pPid psMap
>         then do psMap' <- new psMap with pid appended pPid's children
>                 return tree
>         else do tree' <- insert pPid in the process tree
>                 modify (new psMap with pid appended pPid's children)
>                 return tree'

insertProc was in my first message, and it's like this:

> insertProc :: Pid -> StateT PsMap IO PsInfo
> insertProc pid = do
>   process <- lift $ procInfo pid
>   psMap <- get
>   modify (Map.insert pid process)
>   return (process)

At this point I'm not sure if this design is good or even correct. I'm
mixing (StateT PsMap IO PsInfo) with (StateT PsMap IO PsTree), which I'm
not sure I can do. There is probably a much cleaner way to do this but I
cannot see through the types right now :/

Anyone has any hints on how to make that scheme work?

Thanks,
Andre



More information about the Haskell-Cafe mailing list