71

I have made a file called time.hs. It contains a single function that measures the execution time another function.

Is there a way to import the time.hs file into another Haskell script?

I want something like:

module Main where
import C:\Haskell\time.hs

main = do
    putStrLn "Starting..."
    time $ print answer
    putStrLn "Done."

Where time is defined in the 'time.hs' as:

module time where
Import <necessary modules>

time a = do
start <- getCPUTime
v <- a
end   <- getCPUTime
let diff = (fromIntegral (end - start)) / (10^12)
printf "Computation time: %0.3f sec\n" (diff :: Double)
return v

I don't know how to import or load a separate .hs file. Do I need to compile the time.hs file into a module before importing?

LambdaScientist
  • 435
  • 2
  • 13
Jonno_FTW
  • 8,601
  • 7
  • 58
  • 90

3 Answers3

66

Time.hs:

module Time where
...

script.hs:

import Time
...

Command line:

ghc --make script.hs
yairchu
  • 23,680
  • 7
  • 69
  • 109
  • I learned the long way that in this example `script.hs` must be in your present working directory. This means you can't do `ghc --make path/to/script.hs`, for example. – Jesse Looney Aug 12 '20 at 22:17
16

If the module Time.hs is located in the same directory as your "main" module, you can simply type:

import Time

It is possible to use a hierarchical structure, so that you can write import Utils.Time. As far as I know, the way you want to do it won't work.

For more information on modules, see here Learn You a Haskell, Making Our Own Modules.

Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
Christian
  • 4,261
  • 22
  • 24
4

Say I have two files in the same directory: ModuleA.hs and ModuleB.hs.

ModuleA.hs:

module ModuleA where
...

ModuleB.hs:

module ModuleB where

import ModuleA
...

I can do this:

    ghc -I. --make ModuleB.hs

Note: The module name and the file name must be the same. Otherwise it can't compile. Something like

Could not find module '...'

will occur.

uol3c
  • 559
  • 5
  • 9