[Haskell-cafe] Generic functional references for free, now!

Sterling Clover s.clover at gmail.com
Sat Apr 26 11:41:01 EDT 2008


Recent discussions inspired me to cook up the attached, which through  
controlled abuse of various extensions gives functional references  
for all records deriving Data and Typeable for free, with no template  
haskell necessary. Composition is fully supported, as is  
"overloading" of standard record accessors. For the sake of  
preserving at least mild sanity, the (.) operator is not overloaded,  
and composition is instead provided via an overloaded `o`.

For anyone that doesn't mind the absurdity of how this is  
implemented, it should be suitable for "drop in" use.

For those that do mind the absurdity, it nonetheless serves as a  
proof-of-concept for how far Haskell's reflective capacities can be  
pushed.

Cheers, and happy hacking,
Sterl.

Example usage:

data Test = Test {t1 :: Int, t2 :: Int, t3 :: String, t4 ::  
InnerTest} deriving (Data, Typeable, Show)

data InnerTest = InnerTest {t'1 :: Int, t'2 :: Int, t'3 :: String}  
deriving (Data, Typeable, Show)

testData = Test {t1 = 1, t2 = 2, t3 = "foo", t4 = InnerTest {t'1 = 2,  
t'2 = 3, t'3 = "bar"}}

*GenericFRef> set t1 23 testData
Test {t1 = 23, t2 = 2, t3 = "foo", t4 = InnerTest {t'1 = 2, t'2 = 3,  
t'3 = "bar"}}

*GenericFRef> set (t'1 `o` t4) 23 testData
Test {t1 = 1, t2 = 2, t3 = "foo", t4 = InnerTest {t'1 = 23, t'2 = 3,  
t'3 = "bar"}}

*GenericFRef> update (t2) (\x->x*x) testData
Test {t1 = 1, t2 = 4, t3 = "foo", t4 = InnerTest {t'1 = 2, t'2 = 3,  
t'3 = "bar"}}

*GenericFRef> update (t'2 `o` t4) (\x->x*x) testData
Test {t1 = 1, t2 = 2, t3 = "foo", t4 = InnerTest {t'1 = 2, t'2 = 9,  
t'3 = "bar"}}

p.s. I have a nagging sensation that somebody may have done this  
before, although I can't trace the source.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: GenericFRef.hs
Type: application/octet-stream
Size: 3580 bytes
Desc: not available
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20080426/20054ce2/GenericFRef-0001.obj


More information about the Haskell-Cafe mailing list