Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern functions in haskell?

Tags:

haskell

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.

like image 510
Guillaume Chérel Avatar asked Dec 19 '11 15:12

Guillaume Chérel


2 Answers

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).

like image 56
Daniel Wagner Avatar answered Oct 31 '22 19:10

Daniel Wagner


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.

like image 6
hammar Avatar answered Oct 31 '22 20:10

hammar