Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have sub-modules in Haskell?

Tags:

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
like image 964
vidi Avatar asked Feb 22 '17 11:02

vidi


3 Answers

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)
like image 65
Akash Avatar answered Oct 23 '22 04:10

Akash


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
like image 30
n. 1.8e9-where's-my-share m. Avatar answered Oct 23 '22 04:10

n. 1.8e9-where's-my-share m.


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.

like image 22
Dax Fohl Avatar answered Oct 23 '22 03:10

Dax Fohl