vidi
vidi

Reputation: 2106

Is it possible to have sub-modules in Haskell?

I have this code

module M where

a = 1
b = 2
x = 10
y = 20

...but as the module grows it's difficult to deal with duplicate names.

Is it possible to have namespaces like this?

module M where
  module A where
    a = 1
    b = 2

  module X where
    x = 10
    y = 20

..and then

...
import M

s = A.a + X.y

Upvotes: 10

Views: 3221

Answers (3)

Dax Fohl
Dax Fohl

Reputation: 10781

No you cannot. But your comment mentions you're just looking for a way to avoid naming collisions. For this, you can use the {-# LANGUAGE DuplicateRecordFields #-} extension and the compiler will allow duplicate record field names.

Upvotes: 2

n. m. could be an AI
n. m. could be an AI

Reputation: 120011

There are hierarchical module names. You can have modules named M and M.A and M.X, but modules themselves don't nest, and M is unrelated to M.A as far as the language is concerned.

If you want M to export everything M.A and M.X export, you have to do this explicitly:

module M (module M.A, module M.X) where
import M.A
import M.X
-- rest of M

Upvotes: 5

Akash
Akash

Reputation: 5221

What you proposed isn't currently supported in Haskell AFAIK. That said, nothing's stopping you from creating seemingly namespaced modules. For example:

module Top where

myTopFunc :: a -> Int
myTopFunc _ = 1

and in another file:

module Top.Sub where

mySubFunc :: a -> String
mySubFunc _ = "Haskell"

In addition to this, you have a few more tricks up your sleeves to arrange your modules. If you import a module A into B, you can export A's visible entities from B as if they were its own. Subsequently, on importing B, you'll be able to use those functions/datatypes etc. being oblivious to where they originally came from. An example of this using the modules from above would be:

module Top (
  myTopFunc,
  TS.mySubFunc
  ) where

import qualified Top.Sub as TS

myTopFunc :: a -> Int
myTopFunc _ = 1

Now you can use both functions just by importing Top.

import Top (myTopFunc, mySubFunc)

Upvotes: 17

Related Questions