The perfect-hash-generator package

[ Tags: apache, data-structures, embedded, library, program ] [ Propose Tags ]

A perfect hash function for a set S is a hash function that maps distinct elements in S to a set of integers, with no collisions. A minimal perfect hash function is a perfect hash function that maps n keys to n consecutive integers, e.g. the numbers from 0 to n-1.

In contrast with the PerfectHash package, which is a binding to a C-based library, this package is a fully-native Haskell implementation.

It is intended primarily for generating C code for embedded applications (compare to gperf). The output of this tool is a pair of arrays that can be included in generated C code for allocation-free hash tables.

Though lookups also perform reasonably well for Haskell applications, it hasn't been benchmarked thorougly with respect to other data structures.

This implementation was adapted from Steve Hanov's Blog.


The library is written generically to hash both strings and raw integers according to the FNV-1a algorithm. Integers are split by octets before hashing.

import Data.PerfectHash.Construction (createMinimalPerfectHash)
import qualified Data.HashMap.Strict as HashMap

tuples = [
   (1000, 1)
 , (5555, 2)
 , (9876, 3)

lookup_table = createMinimalPerfectHash $ HashMap.fromList tuples

Generation of C code based on the arrays in lookup_table is left as an exercise to the reader. Algorithm documentation in the Data.PerfectHash.Hashing and Data.PerfectHash.Lookup modules will be helpful.

See the hash-perfectly-strings-demo and hash-perfectly-ints-demo, as well as the test suite, for working examples.

$ stack build
$ stack exec hash-perfectly-strings-demo


Versions,,,,,,,,,,, (info)
Dependencies base (>=4.5 && <5), binary, bytestring, containers, data-ordlist, directory, filepath, hashable, optparse-applicative, perfect-hash-generator, random, text, unordered-containers, vector [details]
License Apache-2.0
Author Karl Ostmo <>
Maintainer Karl Ostmo <>
Category Data Structures, Embedded
Home page
Bug tracker
Source repo head: git clone
Uploaded Sun Feb 18 23:49:30 UTC 2018 by kostmo
Distributions LTSHaskell:, NixOS:, Stackage:
Executables hash-perfectly-strings-demo, hash-perfectly-ints-demo
Downloads 907 total (182 in the last 30 days)
Rating 2.0 (votes: 1) [estimated by rule of succession]
Your Rating
  • λ
  • λ
  • λ
Status Docs available [build log]
Last success reported on 2018-02-19 [all 1 reports]
Hackage Matrix CI




Maintainer's Corner

For package maintainers and hackage trustees