I would like to write a module that uses a function to be defined by the user. For example:
module A
(someFun) where
someFun x = doSomethingWith externFun x
I would like externFun to be defined by the user, in the file importing the module A. Is there a way? Or is it just a bad idea?
I could of course pass externFun as an argument to someFun, But there it doesn't look very convenient: the function to be passed would be the same for each call to someFun.
The other answers are wrong: it is possible! There's a little-used extension called ImplicitParams
made exactly for doing this. For example:
-- A.hs
{-# LANGUAGE ImplicitParams #-}
module A where
someFun x = ?externFun (?externFun x)
-- B.hs
{-# LANGUAGE ImplicitParams #-}
module B where
import A
main = print (someFun 3) where
?externFun = (2*)
In ghci:
Prelude *B> main
12
Voila! More information in the Hugs manual, the GHC manual, and Implicit Parameters: Dynamic Scoping with Static Types (PDF).
No, you can't do this. Passing it as an argument is the way to go. However, you can eliminate the repetition by using partial application. Just do something like this in the other module:
import A (someFun)
someFun' = someFun externFun
Now you can use someFun'
everywhere instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With