Optionally run code if package exists

Go To StackoverFlow.com

1

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?

2012-04-04 01:17
by Vlad the Impala
You could use the while statement to optionally run a program while you have the package it’ll run else the package won’t run - Rico Morgan 2018-04-28 02:01


5

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

2012-04-04 01:30
by ehird


1

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.

2012-04-04 01:21
by Luis Casillas


1

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

2012-04-04 12:16
by Chris Kuklewicz