[Haskell-beginners] Recursive update of Records with IO

Alia alia_khouri at yahoo.com
Mon Oct 10 13:53:17 CEST 2011


Hi folks,



(Apologies if there is duplication, I didn't see my post archived so I assumed I had to subscribe to be able to post)


In the hope of tapping the collective wisdom, I'd like to share a problem which seems to be worth sharing: how to recursively update a single record instance with a list of IO tainted functions.

A simple pure IO-less version of what I am trying to do is probably the best way to explain this:

<pure_version>

module Test

where

data Person = Person {name :: String, age :: Int} deriving Show

setName :: String -> Person -> Person
setName s p = p {name=s}

setAge :: Int -> Person -> Person
setAge i p = p {age=i}

update :: [Person -> Person] -> Person -> Person
update [] p  = p
update
 [f] p = f p
update (f:fs) p = update fs p'
    where
        p' = f p

p1 = Person {name="sue", age=12}
p2 = update [(setName "sam"), (setAge 32)] p1

</pure_version>

This works very nicely. 

Now if the setter functions involve some IO, I believe the type signatures should probably look like this:

setName :: String -> Person -> IO Person
setAge :: Int -> Person -> IO Person
update :: [Person -> IO Person] -> Person -> IO Person

and the setter functions should look like this for example:

setName :: String -> Person -> IO Person
setName s p = do
    putStrLn "setting name"
    return p {name=s}

setAge :: Int -> Person -> IO Person
setAge i p = do
    putStrLn "setting age"
    return p {age=i}

but I'm stuck on how
 the update function would look.. Any help would be much appreciated.

Best,

AK
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20111010/e4231109/attachment.htm>


More information about the Beginners mailing list