[Haskell-cafe] Applying a value to a function generically
Felipe Lessa
felipe.lessa at gmail.com
Wed Jul 14 07:33:49 EDT 2010
On Wed, Jul 14, 2010 at 8:25 AM, Arnaud Bailly <arnaud.oqube at gmail.com> 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.html#v%3Acast
> 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.
More information about the Haskell-Cafe
mailing list