Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/frerich/catamorphism
A package exposing a function for generating catamorphisms.
https://github.com/frerich/catamorphism
catamorphisms haskell haskell-library
Last synced: 12 days ago
JSON representation
A package exposing a function for generating catamorphisms.
- Host: GitHub
- URL: https://github.com/frerich/catamorphism
- Owner: frerich
- License: bsd-3-clause
- Created: 2014-08-17T18:09:10.000Z (over 10 years ago)
- Default Branch: master
- Last Pushed: 2018-04-15T19:54:07.000Z (over 6 years ago)
- Last Synced: 2024-03-14T17:14:22.972Z (10 months ago)
- Topics: catamorphisms, haskell, haskell-library
- Language: Haskell
- Size: 41 KB
- Stars: 28
- Watchers: 3
- Forks: 4
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
catamorphisms
=============[![Build Status](https://travis-ci.org/frerich/catamorphism.svg?branch=master)](https://travis-ci.org/frerich/catamorphism)
This project builds an Haskell module `Data.Morphism.Cata` which exports a
`makeCata` function which can be used to generate
[catamorphisms](http://www.haskell.org/haskellwiki/Catamorphisms) for Haskell
types. The base package features a couple of standard catamorphisms such as
[bool](http://hackage.haskell.org/package/base-4.8.0.0/docs/Data-Bool.html#v:bool),
[maybe](http://hackage.haskell.org/package/base-4.8.0.0/docs/Data-Maybe.html#v:maybe),
[either](http://hackage.haskell.org/package/base-4.8.0.0/docs/Data-Either.html#v:either),
or
[foldr](http://hackage.haskell.org/package/base-4.8.0.0/docs/Prelude.html#v:foldr),
all of which could be generated by 'makeCata'. However, catamorphisms are mostly
useful for custom recursive data structures. For instance, given a simple type
for modelling expressions involving numbers, variables and sums as in``` haskell
{-# LANGUAGE TemplateHaskell #-}import Data.Morphism.Cata
import Data.Maybe (fromJust)data Expr a = Number a
| Variable Char
| Sum (Expr a) (Expr a)
```You can use the following `makeCata` invocation to generate a function for folding `Expr`
values - the function will be called `cataExpr`:``` haskell
{- This 'makeCata' invocation defines a functioncataExpr :: (a -> b) -- Number constructor
-> (Char -> b) -- Variable constructor
-> (b -> b -> b) -- Sum constructor
-> Expr a
-> b
-}
$(makeCata defaultOptions { cataName = "cataExpr" } ''Expr)
```This catamorphism can be used to define a whole bunch of other useful functions such as
``` haskell
-- Evaluate an Expr, given some variable bindings
eval :: Num a => [(Char, a)] -> Expr a -> a
eval vars = cataExpr id (fromJust . (`lookup` vars)) (+)-- Pretty-prints an Expr
pprint :: Show a => Expr a -> String
pprint = cataExpr show show (\a b -> a ++ " + " ++ b)-- Counts the number of variables used in an expr
numVars :: Expr a -> Int
numVars = cataExpr (const 1) (const 0) (+)
```