Vlad the Impala
Vlad the Impala

Reputation: 15882

Optionally run code if package exists

In Python, I can run a bit of code optionally if a given package exists like so:

try:
  import asd
  # do something with asd
except ImportError:
  print "no module asd"

Is there a Haskell equivalent?

Upvotes: 1

Views: 148

Answers (3)

Chris Kuklewicz
Chris Kuklewicz

Reputation: 8153

Also, you might be able to use new libraries at runtime if you use plugins.

Upvotes: 1

ehird
ehird

Reputation: 40797

Not directly, since module imports are resolved at compile-time with GHC. But if you're using Cabal (and you should be!), you can conditionally depend on a package according to a configuration flag, and then use the CPP extension to compile code depending on whether or not that dependency is present:

#if MIN_VERSION_somepackage(0,0,0)
...code using somepackage...
#else
...code not using somepackage...
#endif

This is kind of awkward, though, so I wouldn't recommend using it unless you really need it...

Upvotes: 5

Luis Casillas
Luis Casillas

Reputation: 30237

No. A Haskell compiler will reject any program that imports modules that it can't find, just as it will reject uses of undefined functions.

Upvotes: 1

Related Questions