Haskell Snippet – Summing Series #2

Just a little hack using show to make the earlier summing series example look a bit nicer.

Start with what I had before:

sumseries a b f = sum[f n|n<-[a..b]]

I have swapped around and renamed the arguments a little, just to tidy it up a tad.
Summing the first 5 evens (2 + 4 + 6 + 8 + 10):

*Main> sumseries 1 5 (\r -> 2*r)
30

So, I want to prettify it. I want to use Σ for the sum function. So this is easy, right? Just call the function Σ and be done with it. Not so – Sigma is an uppercase letter, and in haskell, these are reserved for datatypes.

Solution: make a datatype

data Σ a = Σ a a (a -> a)

Sure, we have a datatype, but we can’t call this. Now for the hack:

instance (Show a, Num a, Enum a) => Show (Σ a) where
show (Σ a b f) = show $ sumseries a b f

– when we want to show the datatype, like in ghci’s prompt, we call sumseries and show the result of that instead.

Example:

*Main> Σ 1 5 (\r -> 2*r)
30

or more concisely

*Main> Σ 1 5 (*2)
30

Advertisements
Haskell Snippet – Summing Series #2

2 thoughts on “Haskell Snippet – Summing Series #2

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s