Table of contents
Requirements
You need a working Haskell compiler system: GHC(>=8.6), cabal-install(>=2.4). There are several choices:
-
Use the package manager on your operating system if available:
- Mac users can get them via homebew:
brew install ghc cabal-install
. - Windows users can get them via chocolatey:
choco install ghc cabal
. - Ubuntu users are recommended to use this ppa.
- Mac users can get them via homebew:
-
Setup via ghcup.
-
Download pre-built binaries(GHC, cabal-install) and install manually.
Installation
To use Z-Data package as an example. Add the following lines to your project’s cabal file:
...
build-depends: Z-Data == 1.0.*
Now run cabal build
within your project directory, cabal should be able to download Z-Data dependency automatically. Let’s write a simple TCP echo server just for teaching purpose:
-
Initialize a project with
cabal
.mkdir tcp-echo cd tcp-echo cabal init -i
cabal
will ask you some questions about your project and create atcp-echo.cabal
file. -
Add dependencies.
Now open the
tcp-echo.cabal
file with a text editor, and add the following lines under theexecutable
section:... build-depends: Z-IO == 1.0.*
-
Edit code.
Open
src/Main.hs
and add a simple echo TCP server:import Control.Monad import Z.IO import Z.IO.Network main :: IO () main = do let addr = SocketAddrIPv4 ipv4Loopback 8080 startTCPServer defaultTCPServerConfig{ tcpListenAddr = addr } $ \ tcp -> do i <- newBufferedInput tcp o <- newBufferedOutput tcp forever $ readBuffer i >>= writeBuffer o >> flushBuffer o
-
Build!
Ensure that you have run
cabal update
to get the latest package list.cabal build
will start to download dependencies and build your project. You may see output like this:Resolving dependencies... Build profile: -w ghc-8.6 -O1 In order, the following will be built (use -v for more details): - Z-IO-1.0.0.0 (lib) (requires download & build) - tcp-echo-0.1.0.0 (exe:tcp-echo) (first run) Downloaded Z-IO-1.0.0.0 Starting Z-IO-1.0.0.0 (lib) Building Z-IO-1.0.0.0 (lib) ...
It may take a while to build for the first time because cabal needs to download and build all the dependencies. Build afterward will be faster since dependencies are cached. For reference, on an intel 4th gen core, it takes around 10mins to compile Z-Data and Z-IO. So sit back and relax, or go for a coffee.
After building complete, you can use cabal run
to run your echo server and nc 0.0.0.0 8080
to test it. That’s it, happy hacking!