[Haskell-cafe] introspection | meta data
cryptmaster at hotmail.com
Thu Aug 5 11:47:42 EDT 2004
I recently had to implement an algorthm in C, and found the time to give it
a go in Haskell to aid in learning haskell.
I found myself "needing" runtime meta information on data types (well tuples
which are data (a,b) = (a,b)). Does haskell allow this ?
Basically I need to loop over the fields in my record. I came up with
functions like this:
-- Toggle fields to/from generic value
toggle sf origsf 0 = sf
toggle sf origsf n
| newValue == "*ALL" = newSF
| otherwise = toggle newSF origsf (n-1) -- <---------
Loop through fields by No
newValue = toggleField (getSFField n sf) (getSFField n origsf) --
<---- accessor functions
newSF = setSFField n sf newValue
getSFField :: Int -> SearchFilter -> String
getSFField 1 (x,_,_,_,_) = x
getSFField 2 (_,x,_,_,_) = x
setSFField :: Int -> SearchFilter -> String -> SearchFilter
setSFField 1 (a,b,c,d,e) f = (f,b,c,d,e)
setSFField 2 (a,b,c,d,e) f = (a,f,c,d,e)
The only problem with this is that if I want to add or remove a field, I
need to change a lot of code.
In most OO lanaguages I could use "reflection" to loop through my fields.
In C (which also doesnt have meta data) I got round it by using pointers in
an array. To add or remove a field just requires adding or removing a
pointer to my array which is one line of code.
The only thought I had was of using lists, but the this would mean I loose
pattern matching against all values at once which is appealing for calrify
So what is the general haskell approach to this type of introspection/meta
data problem... ?
Protect your PC - get McAfee.com VirusScan Online
More information about the Haskell-Cafe