Hi everyone! I’m trying to do something in Haskell which is very simple to do in Rust: Write a library with optional dependencies.
To give you an example, say we want to write a new library called length
, whose main feature is a typeclass:
class Length a where
length :: a -> Word
By default, it ships with an implementation for List a
, NonEmpty a
, ZipList a
, CallStack
and ByteArray
, all collection types which exist in base
.
But there are other commonly-used packages containing datatypes that merit a typeclass instance:
-
array
'sArray
andIArray
-
containers
’Map
,Set
,IntMap
,IntSet
,Sequence
(strict and lazy) -
unordered-container
'sHashMap
,HashSet
(strict and lazy) -
vector
's variousVector
types -
bytestring
'sByteString
andShortByteString
(strict and lazy) -
text
'sText
andShortText
(strict and lazy) - etc.
Without optional dependencies, the writer of the length
library has one of two options:
- Unconditionally depend on all these libraries, making the
length
library very heavy-weight for anyone, even when they only use a small subset of the datatypes. - Depend on none of the dependencies, and creating a family of orphan-instance libraries (
length-array
,length-containers
,length-vector
, etc.), asking the consumer to manually install the extra orphans they need.
What I would like to do instead, is to indicate in my cabal file, which dependencies are optional. Then, iff another package (transitively) depends on both me and that other dependency, does the desired functionality get enabled.
Is there a way to do this?