Search code examples
haskellcabal

Invoke the functions in the library built from cabal in Haskell


From the book 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/

For example, this is an example of the Cabal file from Section 2 example.

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

After the cabal build, I can get the dynamic and static libraries compiled.

.
├── 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

Then, how can I use the library functions from other Haskell code (in both ghc and ghci)? For example, src/Chapter2/SimpleFunctions.hs has maxim function, how can I invoke this function compiled in the form of Haskell library?

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 

Solution

  • With cabal install you configure your system to use the library you just created. The library is installed in ~/.cabal/lib.

    enter image description here

    For the usage with ghci, you can import the library.

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

    For the usage with ghc, you also can import the library so that the compiler do the linking automatically.

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

    Compile and run:

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