简体   繁体   English

如何在 Haskell 中导入 .hs 文件

[英]How to import a .hs file in Haskell

I have made a file called time.hs .我制作了一个名为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?有没有办法将time.hs文件导入另一个 Haskell 脚本?

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: 'time.hs' 中的时间定义为:

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.我不知道如何导入或加载单独的.hs文件。 Do I need to compile the time.hs file into a module before importing?导入前是否需要将time.hs文件编译为模块?

Time.hs : Time.hs :

module Time where
...

script.hs : script.hs

import Time
...

Command line:命令行:

ghc --make script.hs

If the module Time.hs is located in the same directory as your "main" module, you can simply type:如果模块Time.hs与“主”模块位于同一目录中,则只需键入:

import Time

It is possible to use a hierarchical structure, so that you can write import Utils.Time .可以使用分层结构,以便您可以编写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 .有关模块的更多信息,请参阅此处向您学习 Haskell,制作我们自己的模块

Say I have two files in the same directory: ModuleA.hs and ModuleB.hs.假设我在同一目录中有两个文件:ModuleA.hs 和 ModuleB.hs。

ModuleA.hs:模块A.hs:

module ModuleA where
...

ModuleB.hs:模块B.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.会发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM