Hastern functions extern?

I would like to write a module that uses a user-defined function. For instance:

module A (someFun) where someFun x = doSomethingWith externFun x 

I would like externFun to be defined by the user in a file importing module A. Is there a way? Or is this just a bad idea?

Of course, I could pass externFun as an argument to someFun, but it doesn’t look very convenient there: the function passed will be the same for every call to someFun.

+6
source share
3 answers

Other answers are incorrect: it is possible! It uses a small extension called ImplicitParams , made just for that. For instance:

 -- 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! For more information, see the Hugs Guide , the GHC Guide, and Implicit Parameters: Dynamic Scaling with Static Types (PDF) .

+8
source

No, you cannot do this. Passing it as an argument is the way to go. However, you can exclude repetition using a partial application. Just do something similar in another module:

 import A (someFun) someFun' = someFun externFun 

Now you can use someFun' everywhere.

+6
source

No, you should take this as an argument. Why do you think this will be the same for every call? It works like any other argument.

0
source

Source: https://habr.com/ru/post/904088/


All Articles