Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Recursive update of Records with IO

17 views
Skip to first unread message

Alia K

unread,
Oct 10, 2011, 4:00:46 AM10/10/11
to
Hi folks,

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

Alia K

unread,
Oct 10, 2011, 10:05:32 AM10/10/11
to
<snip>

With apologies for the cross-post (I wasn't sure this list is active
these days), this question was asked and answered very nicely in the
haskell-beginners forum.

Please see: http://www.haskell.org/pipermail/beginners/2011-October/008688.html
and

Thanks

AK

Nobody

unread,
Oct 10, 2011, 1:13:20 PM10/10/11
to
On Mon, 10 Oct 2011 01:00:46 -0700, Alia K wrote:

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

Probably:

update :: [Person -> IO Person] -> Person -> IO Person

update [] p = return p


update [f] p = f p

update (f:fs) p = f p >>= update fs

0 new messages