Generic programming time!
If I have a function:
f :: a1 -> a2 -> a3 -> ... -> an
and a value
v :: aX -- where 1 <= x < n
Without knowing at compile time which of the arguments of f
the value v
is the right type for (if any), can I partially apply f
to v
? (using Typeable, Data, TH, or any other trick)
Slightly more solidly, can I construct the function g
(below) at run-time? It doesn't actually have to be polymorphic, all my types will be monomorphic!
g :: (a1 -> a2 -> a3 -> a4 -> a5) -> a3 -> (a1 -> a2 -> a4 -> a5)
g f v = \x y z -> f x y v z
I know that, using Typeable (typeRepArgs
specifically), v
is the 3rd argument of f
, but that doesn't mean I have a way to partially apply f
.
My code would probably look like:
import Data.Typeable
data Box = forall a. Box (TyRep, a)
mkBox :: Typeable a => a -> Box
mkBox = (typeOf a, a)
g :: Box -> Box -> [Box]
g (Box (ft,f)) (Box (vt,v)) =
let argNums = [n | n <- [1..nrArgs], isNthArg n vt ft]
in map (mkBox . magicApplyFunction f v) argNums
isNthArg :: Int -> TyRep -> TyRep -> Bool
isNthArg n arg func = Just arg == lookup n (zip [1..] (typeRepArgs func))
nrArgs :: TyRep -> Int
nrArgs = (\x -> x - 1) . length . typeRepArgs
Is there anything that can implement the magicApplyFunction
?
EDIT: I finally got back to playing with this. The magic apply function is:
buildFunc :: f -> x -> Int -> g
buildFunc f x 0 = unsafeCoerce f x
buildFunc f x i =
let !res = \y -> (buildFunc (unsafeCoerce f y) x (i-1))
in unsafeCoerce res