在 Haskell 中调用从 cabal 构建的库中的函数

Invoke the functions in the library built from cabal in Haskell

来自书本Beginning Haskell, I learned that I can build a package from cabal setup file (chapter2.cabal). The source is downloadable from http://www.apress.com/downloadable/download/sample/sample_id/1516/

例如,这是第 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 

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

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

我不明白你说 'how to use the maxmin function from ghc' 是什么意思。我想你的意思是 'how to use maxmin in my programs' (可以用 ghc 编译)。如果您查看 src/Chapter2/SimpleFunctions.hs 的第一行,您会发现它位于名为 Chapter2.SimpleFunctions 的模块中。因此,在您自己的 program/code 中,您需要导入该模块才能使用 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/ 目录中查找文件。

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

对于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)