我想编写一个使用用户定义的函数的模块。例如:
module A
(someFun) where
someFun x = doSomethingWith externFun x
我希望 externFun 由用户在导入模块 A 的文件中定义。有没有办法?或者这只是一个坏主意?
我当然可以将 externFun 作为参数传递给 someFun,但是看起来不太方便:每次调用 someFun 时,要传递的函数都是相同的。
最佳答案
其他答案是错误的:有可能!有一个很少使用的扩展名 ImplicitParams
正是为了这样做。例如:
-- 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*)
在 ghci 中:
Prelude *B> main
12
瞧!更多信息请访问 Hugs manual , GHC manual , 和 Implicit Parameters: Dynamic Scoping with Static Types (PDF) .
关于haskell - Haskell中的外部函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8563542/