2015-03-03 34 views
2

从书Beginning Haskell中,我了解到可以从cabal安装文件(chapter2.cabal)构建一个包。源代码可从http://www.apress.com/downloadable/download/sample/sample_id/1516/在Haskell调用由cabal构建的库中的函数

例如,这是第2节示例中Cabal文件的一个示例。

name:   chapter2 
version:  0.1 
cabal-version: >=1.2 
build-type:  Simple 
author:   Alejandro Serrano 

library 
    hs-source-dirs: src 
    build-depends: base >= 4 
    ghc-options:  -Wall 
    exposed-modules: 
        Chapter2.Section2.Example, 
        Chapter2.SimpleFunctions 
    other-modules: 
        Chapter2.DataTypes, 
        Chapter2.DefaultValues 

cabal build之后,我可以得到动态和静态库的编译。

. 
├── Setup.hs 
├── chapter2.cabal 
├── dist 
│   ├── build 
│   │   ├── Chapter2 
... 
│   │   ├── autogen 
│   │   │   ├── Paths_chapter2.hs 
│   │   │   └── cabal_macros.h 
│   │   ├── libHSchapter2-0.1-ghc7.8.3.dylib <-- dynamic lib 
│   │   └── libHSchapter2-0.1.a <-- static lib 
│   ├── package.conf.inplace 
│   └── setup-config 
└── src 
    └── Chapter2 
     ├── DataTypes.hs 
     ├── DefaultValues.hs 
     ├── Section2 
     │   └── Example.hs 
     └── SimpleFunctions.hs 

然后,我该如何使用其他Haskell代码的库函数(在ghc和ghci中)?例如,src/Chapter2/SimpleFunctions.hs有maxim函数,我怎样才能调用这个以Haskell库的形式编译的函数?

maxmin list = let h = head list 
       in if null (tail list) 
       then (h, h) 
       else (if h > t_max then h else t_max 
         , if h < t_min then h else t_min) 
         where t = maxmin (tail list) 
          t_max = fst t 
          t_min = snd t 

回答

0

使用cabal install您将您的系统配置为使用您刚刚创建的库。该库安装在~/.cabal/lib

enter image description here

对于使用与ghci,您可以导入库。

Prelude> import Chapter2.SimpleFunctions 
Prelude Chapter2.SimpleFunctions> maxmin [1,2] 
(2,1) 

对于ghc使用,也可以导入库,这样编译器就自动连接。

import Chapter2.SimpleFunctions 

main :: IO() 
main = putStrLn $ show $ maxmin [1,2,3] 

编译并运行:

chapter2> ghc ex.hs 
[1 of 1] Compiling Main    (ex.hs, ex.o) 
Linking ex ... 
chapter2> ./ex 
(3,1) 
1

要使用maxmin从ghci中只加载源文件:

chapter2$ ghci 
> :l src/Chapter2/SimpleFunctions 
> maxmin [1,2,3] 
(3,1) 

我不知道你的意思说,当“如何使用maxmin功能从GHC”。我想你的意思是'如何在我的程序中使用maxmin'(可以用ghc编译)。如果你看第一行src/Chapter2/SimpleFunctions.hs,你可以看到它在一个名为Chapter2.SimpleFunctions的模块中。因此,在您自己的程序/代码中,您需要导入该模块才能使用maxmin。作为这样一个例子:

chapter2$ cat Test.hs 

-- In your favorite editor write down this file. 
import Chapter2.SimpleFunctions 

main = print $ maxmin [1,2,3] 

chapter2$ ghc Test.hs -i.:src/ 
chapter2$ ./Test 
(3,1) 

ghc Test.hs -i.:src/是特灵GHC查找文件在当前和src/目录。