2
votes

Hello i was wondering how do you solve circular dependency in Haskell

I have :
Module for a type.

module Company where

import Tclass

data Worker=Worker{
    age::Int,
    name::String,
    title::Title,
    income::Int
}

data Title=Manager | Dev | Tester deriving (Show)


data Company=Company{
    cname::String,
    people::[Worker],
    yf::Int
}

Module for the instance of the typeclass

module Tclass where
import System.Environment
import Company

class Console a where
    wLine::a->IO()
    rLine::IO String->a

instance Show Worker where
    show w="to be defined"
    print =putStr . show 

If i just want to load the type in ghci and use it ; how do i import them without getting the error:

Module imports form a cycle:
         module `Tclass' (.\Tclass.hs)
        imports `Company' (Company.hs)
  which imports `Tclass' (.\Tclass.hs)

P.S I have tried creating a auxiliary module that imports the two modules and the two modules would import it too,but no luck with this one either :

module Au where
 import Tclass
 import Company

module Company
 import Au

module Tclass 
 import Au
1
It looks like the first module should not import the second, can you remove the line import Tclass and retry?Olivier Sohn
But if i do not import the TClass inside the Company module i can not use instance of Show for Worker type.Bercovici Adrian
Then can you move the Show instance to the other module ? defining an instance in another module than the data definition is bad practice (you'll have the orphan instance warning)Olivier Sohn
You can have the types in a specific module, but with their instances.Olivier Sohn
It's not part of the question but reading your code I would suggest that you read about strict fields in data records : stackoverflow.com/questions/8576795/… it might be helpful here.Olivier Sohn

1 Answers

3
votes

Moving the Show instance to the other module, you can break the cycle:

module Tclass where
import System.Environment
import Company

class Console a where
    wLine::a->IO()
    rLine::IO String->a

and

module Company where

data Worker=Worker{
    age::Int,
    name::String,
    title::Title,
    income::Int
}
instance Show Worker where
    show w="to be defined"
    print =putStr . show 

data Title=Manager | Dev | Tester deriving (Show)

data Company=Company{
    cname::String,
    people::[Worker],
    yf::Int
}