Applying a value to a function generically

Hello, I would like to construct a collection of function-like objects on which I could apply some value, in a typesafe and clean way. Let's say I have something like this:
data Fun = forall a b . F (a -> b) type Callables = Map String Fun
I would like to be able to write:
invoke :: Callables -> a -> String -> b invoke m d k = case lookup k m of Just (F f) -> f d Nothing -> error $ "unable to find function for key " ++ k
which of course does not compile nor even make sense. I suspect I need to have more information in Fun to be able to apply functions correctly, but don't know where to look at. I read recently an article about implicit configurations that used some type wizardry to ensure correct and typesafe use of external data and sounded pretty cool, (http://www.cs.rutgers.edu/~ccshan/prepose/prepose.pdf) but I suspect this is 1) too complex for me an 2) overkill for my problem. Could someone point me in the right direction ? Thanks in advance Arnaud

On Wed, Jul 14, 2010 at 8:25 AM, Arnaud Bailly
Hello, I would like to construct a collection of function-like objects on which I could apply some value, in a typesafe and clean way.
You could use Data.Typeable.cast [1] [1] http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Data-Typeable...
Let's say I have something like this:
data Fun = forall a b . F (a -> b) type Callables = Map String Fun
Sorry, but using GADT syntax: data Fun where F :: (Typeable a, Typeable b) => (a -> b) -> Fun
I would like to be able to write:
invoke :: Callables -> a -> String -> b invoke m d k = case lookup k m of Just (F f) -> f d Nothing -> error $ "unable to find function for key " ++ k
Untested: invoke :: (Typeable a, Typeable b) => Callables -> a -> String -> Maybe b invoke m d k = do F f <- lookup k m arg <- cast d cast (f arg) HTH! -- Felipe.

2010/7/14 Felipe Lessa
On Wed, Jul 14, 2010 at 8:25 AM, Arnaud Bailly
wrote: Hello, I would like to construct a collection of function-like objects on which I could apply some value, in a typesafe and clean way.
You could use Data.Typeable.cast [1]
[1] http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Data-Typeable... [snip]
Or maybe Data.Dynamic with type Callables = Map String Dynamic You can extract the function with fromDynamic in a type-safe way (it returns a Maybe). Probalby you might want 'invoke' to return a Maybe too (just like Felipe did). Cheers, Thu
participants (3)
-
Arnaud Bailly
-
Felipe Lessa
-
Vo Minh Thu