13

Haskell recursive / circular module definitions?

 3 years ago
source link: https://www.codesd.com/item/haskell-recursive-circular-module-definitions.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Haskell recursive / circular module definitions?

advertisements

I have two modules which imports each other. Haskell doesn't support recursive modules. So how can i rewrite my data types without needs circular module system.

Here is my Character.hs

module Character where
import ItemSystem

data Character = Character { name :: String, items :: [Item] }

an here is ItemSystem.hs

module Item where
import Character

data ItemEffect = CharacterEffect (Character -> Character)
                | ItemEffect      (Item -> Item)

data Item = Item { name :: String, weight :: Int, effect :: ItemEffect }

UPDATE: I will write my all datatypes into one module :( .


Create a third module for the mutually dependent parts:

module Internal where

data Character = Character { name :: String, items :: [Item] }

data ItemEffect = CharacterEffect (Character -> Character)
                | ItemEffect      (Item -> Item)

data Item = Item { name :: String, weight :: Int, effect :: ItemEffect }

Then import it from both the other modules and optionally re-export the stuff you want available from each:

module Character (Character(..), {- etc -}) where

import Internal

-- non-mutually dependent stuff

module Item (Item(..), ItemEffect(..), {- etc -}) where

import Internal

-- non-mutually dependent stuff

If this is in a Cabal package, you can then hide the Internal module from the rest of the world by putting it in the Other-modules section instead of Exported-modules.

For completeness: GHC does support mutually recursive modules, but I would not recommend that for simple cases like this.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK