This is the first part of a hands-on guide on creating a Haskell based web service. No previous knowledge of haskell is required. However, basic understanding of RESTful web services is assumed. Other posts in this series: part 2, part 3.
Over the last couple of weeks, I spent some time creating a simple Haskell web application. As it is with every new language or platform, I had to set up and understand a lot of things to get my app up and running. I’m sharing my experience here, hoping that it will help others who might be inclined to get into the Haskell world.
We’ll go through the following 3 steps:
- Set up the development environment
- Build and package a simple app using
- Run a basic Haskell web app using Scotty
1. Set up the development environment
You may skip this step if you already have
cabal installed on your system.
Install the Haskell Platform (GHC)
GHC is the Glasgow Haskell Compiler package which provides you the compiler (
ghc) as well as a REPL (
ghci). Cabal is Haskell’s package manager and works similar to
sbt (Scala) and
% brew update % brew install ghc cabal-install
Haskell REPL (
Next, we’ll start the Haskell REPL which is called
ghci and get comfortable with a bit of Haskell syntax.
Let’s define two simple functions that convert temperature values between celsius and fahrenheit:
Prelude> let f2c f = (f — 32) * 5 / 9 Prelude> let c2f c = (c * 9/5) + 32
Now, we can call these functions to get converted temperatures:
Prelude> f2c 800 426.6666666666667 Prelude> c2f 100 212.0 Prelude> c2f 37 98.6 Prelude> <Ctrl+D> — To exit
Run Haskell Scripts (
We’ll move these function definitions to a haskell source file and define a main method that prints the converted temperature value.
Copy the following code into a file named
c2f c = (c * 9/5) + 32 main = do print (c2f 37)
Note: We used
let for defining functions inside
ghci. When writing Haskell source files, you don’t require
Run the script from the command line using
% runhaskell c2f.hs 98.6
Build an executable
runhaskell makes the development cycle easier when you are writing a Haskell application. But you can also create executable files using the
ghc compiler. Let’s convert our script to a binary and then run it:
% ghc c2f.hs [1 of 1] Compiling Main ( c2f.hs, c2f.o ) Linking c2f … % ls c2f c2f.hi c2f.hs c2f.o % ./c2f 98.6
Load your source files into
You can load external source files into
ghci by using the
:l command. Let’s start a
ghci session and load our
Main.hs file so that we can use the
c2f function inside the REPL:
% ghci GHCi, version 7.10.2: http://www.haskell.org/ghc/ :? for help Prelude> :load Main.hs [1 of 1] Compiling Main ( Main.hs, interpreted ) Ok, modules loaded: Main. *Main> c2f 37 98.6
Now that our development environment is set up, in part 2 we’ll move on to building a simple app using
cabal which is Haskell’s package manager.
(open source and trusted by devs everywhere ❤️)