Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example on the use of backpack

I'm looking at the references at the backpack wiki trying to understand in which cases the use of backpack would be considered appropriate over other Haskell features like type-classes and type-families.

In particular, in this blog-post by the author of backpack, an example is presented that implements a simple matcher for regular expressions. However as far as I understand, the same module could have been coded using type families.

Are there any examples that concisely show the advantages of backpack over more traditional Haskell features? If the example I referred above is a good one, do you know why a solution that uses type families would be subpar?

like image 488
Damian Nadales Avatar asked Sep 27 '18 13:09

Damian Nadales


Video Answer


1 Answers

Main benefits of Backpack:

  1. Guaranteed absence of performance overhead (using typeclasses can have performance overhead due to how they are implemented in Haskell). This is extremely important when working with string data types, parsers, containers, etc.
  2. Cleaner and nicer code compared to usages of typeclasses or type families.

I wrote a blog post about one particular usage of Backpack: implementing a polymorphic interface for containers data structures:

  • Picnic: put containers into a backpack

Having such an interface for containers allows to:

  1. Write polymorphic functions that work with any container (e.g. Map, HashMap and IntMap).
  2. Write single test-suite for properties of containers and use it in every package without code duplication.
  3. Write a single benchmark and use with every containers data structure without performance overhead.

If terms of making code cleaner. This is the signature of the groupBy function implemented using Backpack:

groupBy :: forall k f a . (Foldable f, Key k) => (a -> k) -> f a -> Map k (NonEmpty a)

It's clear, and it's just a plain Haskell. If you implement an interface for containers using typeclasses and type families (this is done in relude, this signature will look like this:

groupBy
    :: forall f t a . (Foldable f, DynamicMap t, Val t ~ NonEmpty a, Monoid t)
    => (a -> Key t) -> f a -> t

Much harder to read and understand.

Also it was discussed recently that Backpack can help with avoiding CPP when you need to compile Haskell code targetting different platforms (aka conditional compilation).

like image 134
Shersh Avatar answered Sep 20 '22 19:09

Shersh