Home > database >  Importing Modules in Haskell (beginner)
Importing Modules in Haskell (beginner)

Time:12-30

I've just begun learning Haskell today and have been alternating between video lectures, programming exercises and the Project Directory Structure

My main, after modification looks like

module Main (main) where

import Lib
import SpaceAge -- my attempt to import custom module

main :: IO ()
main = ageOn  -- Previously someFunc from Lib.hs

where the custom module SpaceAge.hs which rests in the src subdir looks like this.

-- This script is from one of the programming exercises
import SpaceAge ( Planet(..), ageOn ) where

data Planet = Mercury
    | Venus
    | Earth
    | Mars
    | Jupiter
    | Saturn
    | Uranus
    | Neptune

ageOn :: Planet -> Float -> Float
ageOn planet seconds = seconds / earthYear * planetMultiplier
    where
        planetMultiplier = case planet of
            Mercury -> 0.2408467
            Venus ->   0.61519726
            Earth ->   1
            Mars ->    1.8808158
            Jupiter -> 11.862615
            Saturn ->  29.447498
            Uranus ->  84.016846
            Neptune -> 164.79132
        earthYear = 31557600

Running this project in VS Code yields the error: parse error on input 'where' on on Line 1 after the module is interpreted. I've been toiling for about an hour now troubleshooting and googling to no avail. I found in the eBook that custom modules should be in the same directory as the Main.hs file. I tried this but get the error can't find file: .\Ex2\src\SpaceAge.hs.

Can somebody tell me if my error lies in one of these things?

  1. SpaceAge.hs needs to be in the same directory as Main.hs? If so, why does this reference issue not affect the default Lib.hs?
  2. The SpaceAge.hs file contains errors?
  3. Need to modify package.yaml?
  4. Type error on Main.main?

If more detail to the question is needed - I will edit the question accordingly. Thank you.


I have read the following similar questions:

  1. Unable to import modules in haskell (not the same error message)
  2. Importing Crypto Modules in Haskell (does not seem pertinent to my issue)

CodePudding user response:

This is a simple typo. Where you write

import SpaceAge ( Planet(..), ageOn ) where

you should write

module SpaceAge ( Planet(..), ageOn ) where

The import statement is for importing names from a different module; You need the module statement to declare a module name (and export list).

  • Related