DDC/PolymorphicUpdate

From HaskellWiki
< DDC
Revision as of 06:27, 19 March 2008 by Benl23 (talk | contribs)
Jump to navigation Jump to search

Get/Set

Consider the following function:

makeGetSet :: a -> (() -> a, a -> ())
makeGetSet x
 = do 	box	= Just x
	get ()	= case box of { Just z -> z; }
	set z	= box#x #= z
	(get, set)

This function allocates a box which can store a value and returns a tuple of functions which can be used to get and set that value.

As the function is polymorphic, we can create boxes of whatever type we would like:

main ()
 = do	getSet	= makeGetSet 5

 	out $ fst getSet ()   -- prints '5'

	snd getSet 23         -- update the box
	out $ fst getSet ()   -- prints '23'