Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a .hs file in Haskell

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?

like image 400
Jonno_FTW Avatar asked Sep 17 '09 12:09

Jonno_FTW


People also ask

How do I import a file into Haskell?

The syntax for importing modules in a Haskell script is import <module name>. This must be done before defining any functions, so imports are usually done at the top of the file. One script can, of course, import several modules. Just put each import statement into a separate line.

What is a qualified import in Haskell?

A qualified import allows using functions with the same name imported from several modules, e.g. map from the Prelude and map from Data.

How do you define a module in Haskell?

Haskell's module design is relatively conservative: the name-space of modules is completely flat, and modules are in no way "first-class." Module names are alphanumeric and must begin with an uppercase letter. There is no formal connection between a Haskell module and the file system that would (typically) support it.


2 Answers

Time.hs:

module Time where ... 

script.hs:

import Time ... 

Command line:

ghc --make script.hs 
like image 131
yairchu Avatar answered Oct 08 '22 21:10

yairchu


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.

like image 21
Christian Avatar answered Oct 08 '22 20:10

Christian