Getting started with Haskell, stack and spacemacs

It has been very long time since my last blog post. During this period I have become big enthusiast of functional programming, especially using Haskell language. In this and next posts I am going to show that Haskell can be very pleasant to use and with proper tools we are able to develop applications without unnecessary burden.

Recently, many useful tools and editors emerged and they are really easy and convenient to use. In this post I intend to present toolchain that I am using in my everyday Haskell programming.

This post is not an introduction to Haskell language. It is meant to describe how to setup Haskell with stack build tool and spacemacs as an editor. I am also planning to write a post about Haskell basics and its usage in my little project in series of the next posts.

The only necessary prerequisite is having the most recent version of Emacs installed on your system.

New project build/management tool – stack

Managing dependencies and build process is always a gruesome task and there are many tools to ease this work. In Haskell most popular dependency management tool is cabal. It is based on Hackage repository (https://hackage.haskell.org).
One of the desired features of build tools are reproducible builds. We would like to build project in new environment or on the new developer’s machine and have the same outcome in every situation. This would require same compiler version, same libraries etc.
Lately, new tool came out – stack (https://github.com/commercialhaskell/stack). It is aimed at reproducible builds and simple project management. Stack takes care of proper configuration of your project environment.
Stack achieves reproducible builds by using curated snapshot packages managed by special versioned resolvers. It uses cabal as a package manager. Packages are grouped into resolvers. There are two types of resolvers: LTS (long term support) and nightly. The latter contains packages in fresh version but there is also a drawback – potential instability. On the other hand, LTS resolvers contain fixed version of packages which are tested and should not cause any problems. If you are not in need of using latest packages version, LTS resolver should entirely satisfy your project needs.

What is more, stack can also download and setup locally Haskell compiler in version required by your project.

stack in action

Using stack to create new project is really easy. After installing it on our machine (description of installation is included in documentation on project’s GitHub page I linked above), all we need to do to create new project is execute below steps in our terminal:
stack new hello-haskell
cd hello-haskell
stack setup
stack build
stack exec hello-haskell
These commands create new project with name hello-haskell. stack setup initialises environment, install compiler (if it will be required) and necessary libraries for project. stack build builds and compiles project. stack exec … executes executable program built earlier.

If you would like to play around with your project’s code you should type stack ghci in your terminal – this will launch Haskell interactive console – ghci – in version specified in project configuration.

Another stack command worth mentioning is stack test which executes test suites declared in test/ directory.

Dependencies and project settings are placed in hello-haskell.cabal file. It is standard cabal configuration file where we can add desired libraries, set project version, licence, link to the repository and so on. I suggest reading some cabal documentation if you have any doubts but in my opinion this file is very easy and straightforward to edit.

Settings specific for stack are placed in stack.yaml file. Most important option is resolver – which influences version of GHC compiler and libraries your project will be using.

There is one thing you might encounter while setting up project dependencies. What if you need library that is not present in any of stack resolvers? Well, then we must go to stack.yaml file and edit or add section:

extra-deps:
- Vec-1.0.5

With this information stack will download and build desired package from hackage repositories. In my case I needed Vec library so I added it on a list with full name containing version number.

All details and gotchas are described in stack’s Wiki on GitHub. Be sure to check it out frequently as stack is still very young tool and it can change quite often. Documentation is very strong point of stack as it describes very well many aspects of its usages.

 

Powerful editor in new edition – spacemacs

I have spent a lot of time searching for editor that is easy to use with Haskell and that integrates well with its tools like REPL. I’ve been working with Sublime Text for some time as it is integrated quite well with Haskell when using SublimeHaskell package. However, recently I’ve discovered spacemacs project.
spacemacs (https://github.com/syl20bnr/spacemacs) is a easy-to-use kit for Emacs focused on ergonomics. What is great about it is that it embraces Evil mode of Emacs which mimics Vim-style editing and document navigation. With this feature spacemacs is really straightforward for users which know Vim. It is also possible to mix Vim and Emacs style in the same time.

In my opinion, it is really great feature as we can use this editor in the way we like more or is more convenient to us. Whether we are Vim-lovers or Emacs-fans or we want to mix them both – spacemacs allows to work in whatever style we like. I personally use mostly Vim-like mode with only few of original Emacs commands and with spacemacs shortcuts for many actions.

spacemacs is based on layers which add additional functionalities to editor. It can enrich our development environment with syntax completion, git integration, code completion and integration with build tools for many languages.

One of these layers is haskell layer. It supports this language quite well with syntax checking, code suggestions, built-in REPL and code templates for common patterns.

I refer to the official documentation for detailed installation instruction on various platform. After we are ready and spacemacs is on our disk, we can proceed.

Entire spacemacs configuration is placed in .spacemacs file in your home directory. This file is written in Lisp-like language and contains many options to change or add. Here is my current .spacemacs file on what this post section is based: 
https://gist.github.com/rafalnowak/202aba0ee7986515345b

In dotspacemacs-configuration-layers we need to add haskell layer (I also recommend setting auto-completion and syntax-checking layers as well). In order to get layer to work properly, we need to install some additional packages:
stack install stylish-haskell hlint hasktags
Next step is adding these two settings to .spacemacs just after text ;; User initialization goes here:
(add-hook 'haskell-mode-hook 'turn-on-haskell-indentation)
(add-to-list 'exec-path "~/.local/bin/")

It makes spacemacs aware of Haskell indentation style and adds binaries installed by stack to path. It is important as we want to make our editor able to run Haskell tools. 

Full description, as well as platform specific problems, are listed in Haskell layer documentation: https://github.com/syl20bnr/spacemacs/tree/master/layers/%2Blang/haskell There is also a list of useful shortcuts used by this layer.

One essential note: if you wish to use spacemacs with ghc-mod integration, you will need to install ghc-mod at least in version 5.4.0.0. Previous versions do not work properly with Haskell layer and stack. To install ghc-mod in this version you must add cabal-helper-0.6.1.0 to your extra-deps section in stack.yaml and run 

stack install ghc-mod

Which should proceed now without problems.  

After this configuration we are ready to use all power of Haskell and stack in our projects. We will also have solid support from editor. If you have followed steps above, you will see that spacemacs is colouring Haskell syntax, checking its correctness and giving you code completion tips. There is also interactive console for Haskell available under SPC m s s keys combination which makes quick testing of new functions possible. 

Unfortunately, there are some disadvantages of spacemacs. For me, the biggest drawdown is its responsivity. Sometimes during code completion or syntax checking it can hang application for a second or less.

 

Summary

As we could see, Haskell with stack and spacemacs is really powerful yet still simple to use. With stack we can achieve reproducible builds with specific compiler and libraries versions as well as easy project management. spacemacs allows us to create code quickly with support for Haskell syntax, build tools and code completion.

In my next post I am going to describe my experiences with my first bigger Haskell project – functional ray tracer I have been working on recently – https://github.com/rafalnowak/RaytracaH

 

You May Also Like

How to automate tests with Groovy 2.0, Spock and Gradle

This is the launch of the 1st blog in my life, so cheers and have a nice reading!

y u no test?

Couple of years ago I wasn't a big fan of unit testing. It was obvious to me that well prepared unit tests are crucial though. I didn't known why exactly crucial yet then. I just felt they are important. My disliking to write automation tests was mostly related to the effort necessary to prepare them. Also a spaghetti code was easily spotted in test sources.

Some goodies at hand

Now I know! Test are crucial to get a better design and a confidence. Confidence to improve without a hesitation. Moreover, now I have the tool to make test automation easy as Sunday morning... I'm talking about the Spock Framework. If you got here probably already know what the Spock is, so I won't introduce it. Enough to say that Spock is an awesome unit testing tool which, thanks to Groovy AST Transformation, simplifies creation of tests greatly.

An obstacle

The point is, since a new major version of Groovy has been released (2.0), there is no matching version of Spock available yet.

What now?

Well, in a matter of fact there is such a version. It's still under development though. It can be obtained from this Maven repository. We can of course use the Maven to build a project and run tests. But why not to go even more "groovy" way? XML is not for humans, is it? Lets use Gradle.

The build file

Update: at the end of the post is updated version of the build file.
apply plugin: 'groovy'
apply plugin: 'idea'

def langLevel = 1.7

sourceCompatibility = langLevel
targetCompatibility = langLevel

group = 'com.tamashumi.example.testwithspock'
version = '0.1'

repositories {
mavenLocal()
mavenCentral()
maven { url 'http://oss.sonatype.org/content/repositories/snapshots/' }
}

dependencies {
groovy 'org.codehaus.groovy:groovy-all:2.0.1'
testCompile 'org.spockframework:spock-core:0.7-groovy-2.0-SNAPSHOT'
}

idea {
project {
jdkName = langLevel
languageLevel = langLevel
}
}
As you can see the build.gradle file is almost self-explanatory. Groovy plugin is applied to compile groovy code. It needs groovy-all.jar - declared in version 2.0 at dependencies block just next to Spock in version 0.7. What's most important, mentioned Maven repository URL is added at repositories block.

Project structure and execution

Gradle's default project directory structure is similar to Maven's one. Unfortunately there is no 'create project' task and you have to create it by hand. It's not a big obstacle though. The structure you will create will more or less look as follows:
<project root>

├── build.gradle
└── src
├── main
│ ├── groovy
└── test
└── groovy
To build a project now you can type command gradle build or gradle test to only run tests.

How about Java?

You can test native Java code with Spock. Just add src/main/java directory and a following line to the build.gradle:
apply plugin: 'java'
This way if you don't want or just can't deploy Groovy compiled stuff into your production JVM for any reason, still whole goodness of testing with Spock and Groovy is at your hand.

A silly-simple example

Just to show that it works, here you go with a basic example.

Java simple example class:

public class SimpleJavaClass {

public int sumAll(int... args) {

int sum = 0;

for (int arg : args){
sum += arg;
}

return sum;
}
}

Groovy simple example class:

class SimpleGroovyClass {

String concatenateAll(char separator, String... args) {

args.join(separator as String)
}
}

The test, uhm... I mean the Specification:

class JustASpecification extends Specification {

@Unroll('Sums integers #integers into: #expectedResult')
def "Can sum different amount of integers"() {

given:
def instance = new SimpleJavaClass()

when:
def result = instance.sumAll(* integers)

then:
result == expectedResult

where:
expectedResult | integers
11 | [3, 3, 5]
8 | [3, 5]
254 | [2, 4, 8, 16, 32, 64, 128]
22 | [7, 5, 6, 2, 2]
}

@Unroll('Concatenates strings #strings with separator "#separator" into: #expectedResult')
def "Can concatenate different amount of integers with a specified separator"() {

given:
def instance = new SimpleGroovyClass()

when:
def result = instance.concatenateAll(separator, * strings)

then:
result == expectedResult

where:
expectedResult | separator | strings
'Whasup dude?' | ' ' as char | ['Whasup', 'dude?']
'2012/09/15' | '/' as char | ['2012', '09', '15']
'nice-to-meet-you' | '-' as char | ['nice', 'to', 'meet', 'you']
}
}
To run tests with Gradle simply execute command gradle test. Test reports can be found at <project root>/build/reports/tests/index.html and look kind a like this.


Please note that, thanks to @Unroll annotation, test is executed once per each parameters row in the 'table' at specification's where: block. This isn't a Java label, but a AST transformation magic.

IDE integration

Gradle's plugin for Iintellij Idea

I've added also Intellij Idea plugin for IDE project generation and some configuration for it (IDE's JDK name). To generate Idea's project files just run command: gradle idea There are available Eclipse and Netbeans plugins too, however I haven't tested them. Idea's one works well.

Intellij Idea's plugins for Gradle

Idea itself has a light Gradle support built-in on its own. To not get confused: Gradle has plugin for Idea and Idea has plugin for Gradle. To get even more 'pluginated', there is also JetGradle plugin within Idea. However I haven't found good reason for it's existence - well, maybe excluding one. It shows dependency tree. There is a bug though - JetGradle work's fine only for lang level 1.6. Strangely all the plugins together do not conflict each other. They even give complementary, quite useful tool set.

Running tests under IDE

Jest to add something sweet this is how Specification looks when run with jUnit  runner under Intellij Idea (right mouse button on JustASpecification class or whole folder of specification extending classes and select "Run ...". You'll see a nice view like this.

Building web application

If you need to build Java web application and bundle it as war archive just add plugin by typing the line
apply plugin: 'war'
in the build.gradle file and create a directory src/main/webapp.

Want to know more?

If you haven't heard about Spock or Gradle before or just curious, check the following links:

What next?

The last thing left is to write the real production code you are about to test. No matter will it be Groovy or Java, I leave this to your need and invention. Of course, you are welcome to post a comments here. I'll answer or even write some more posts about the subject.

Important update

Spock version 0.7 has been released, so the above build file doesn't work anymore. It's easy to fix it though. Just remove last dash and a word SNAPSHOT from Spock dependency declaration. Other important thing is that now spock-core depends on groovy-all-2.0.5, so to avoid dependency conflict groovy dependency should be changed from version 2.0.1 to 2.0.5.
Besides oss.sonata.org snapshots maven repository can be removed. No obstacles any more and the build file now looks as follows:
apply plugin: 'groovy'
apply plugin: 'idea'

def langLevel = 1.7

sourceCompatibility = langLevel
targetCompatibility = langLevel

group = 'com.tamashumi.example.testwithspock'
version = '0.1'

repositories {
mavenLocal()
mavenCentral()
}

dependencies {
groovy 'org.codehaus.groovy:groovy-all:2.0.5'
testCompile 'org.spockframework:spock-core:0.7-groovy-2.0'
}

idea {
project {
jdkName = langLevel
languageLevel = langLevel
}
}

Hibernate hbm2ddl won’t create schema before creating tables

Situation I have a local H2 in memory database for integration tests and an Oracle db for production. I do not control the Oracle DB model. The in memory H2 database is created automatically by adding <prop key="hibernate.hbm2ddl.auto">update&l...Situation I have a local H2 in memory database for integration tests and an Oracle db for production. I do not control the Oracle DB model. The in memory H2 database is created automatically by adding <prop key="hibernate.hbm2ddl.auto">update&l...