HaskSymb: An Experiment in Haskell Symbolic Algebra

One interesting detour I took this last month was writing a toy Haskell Symbolic Algebra library, HaskSymb. It takes advantage of Quasi-Quoters and View Patterns to do awesome math pattern matching and enable one to write beautiful code.

An example of its use:

> -- Let's make some variables!
> let (a,b)  = (V "a", V "b")
> -- Basic Expression manipulation
> (a+1)^3
(a + 1)³
> expand $ (a+1)^3
a³ + a² + a² + a² + a + a + a + 1
> collectTerms $ expand $ (a+1)^3
a³ + 3a² + 3a + 1

The interesting part, however, is the code for expand, collectTerms and friends. It’s extremely pretty. For example:

expand [m| a+b |] = expand a + expand b
expand [m|a*(b+c)|] = expand (a*b) + expand (a*c)
expand a = a

Read more on github. You can also find some discussion on the Haskell reddit.

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: