Difference between revisions of "DDC/PolymorphicUpdate"
< DDC
Jump to navigation
Jump to search
Line 12: | Line 12: | ||
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. |
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: |
||
+ | |||
+ | <haskell> |
||
+ | main () |
||
+ | = do getSet = makeGetSet 5 |
||
+ | |||
+ | out $ fst getSet () -- prints '5' |
||
+ | |||
+ | snd getSet 23 -- update the box |
||
+ | out $ fst getSet () -- prints '23' |
||
+ | </haskell> |
Revision as of 06:27, 19 March 2008
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'