some idiot
some idiot

Reputation: 191

Install local library

How can I "install" a local (ie it is on my hard-drive, not on the internet) .hs file to use it across multiple programs? Specifically, if I edit the library, those edits should be available to all programs, so no copy-pasting the library into every program’s directory.

To compile my programs, I still want to type ghc main.hs, not a page of file-paths.

This may be obvious from the above, but I don’t have any knowledge of cabal.

Upvotes: 2

Views: 506

Answers (1)

leftaroundabout
leftaroundabout

Reputation: 120751

  1. Make sure you have the proper Haskell platform installed, including cabal. Alternatively you can use stack, which is more modern and in many ways better, but IMO cabal is still more practical for a simple project like yours.
    The following assumes you use cabal on a typical Linux machine.

  2. If not already done, give your file a meaningful hierarchical module name, according to what it does. module Video.Demuxing.FFMPEG or Data.List.Shuffle.Deterministic, for example. Let's assume you call it Foo.Bar.Baz. I.e. the file should begin with

    module Foo.Bar.Baz where
    ... -- start code
    
  3. Put the file in a corresponding folder structure, i.e.

    1. if not already done, make a new project directory, for example

      mkdir /home/Uꜱᴇʀɴᴀᴍᴇ/haskell/foobar
      cd /home/Uꜱᴇʀɴᴀᴍᴇ/haskell/foobar
      
    2. In that project directory make a subdirectory Foo, therein a directory Bar, and put your file in it as Baz.hs.

      mkdir -p Foo/Bar
      cp WʜᴇʀᴇEᴠᴇʀ/Yᴏᴜʀ/Fɪʟᴇ/Wᴀꜱ/Bᴇꜰᴏʀᴇ.hs Foo/Bar/Baz.hs
      
  4. Make the file part of a new cabal library.

    cabal init
    

    This will ask you a couple of questions, hopefully it'll be clear what to choose. For the most part, the defaults will be fine, in that case always just press enter.

  5. Put everything under version control, if you haven't already. (If you don't know what this is, I suggest you read some Github tutorials. You can skip this step, but the sooner you accustom yourself to some VCS, the better.)

  6. Install your project locally.

    cabal install
    
  7. If everything has worked without errors, you can then, in a Haskell file stored in somewhere else on the computer, simply

    import Foo.Bar.Baz
    

    and have everything availably you've defined in that project module. No need to tell GHC where Foo.Bar.Baz is stored when compiling, it has already registered that at this point. You can also launch up ghci anywhere and :m +Foo.Bar.Baz.

Upvotes: 1

Related Questions