Lazy Arithmetic in Haskell

24/03/2010

We don’t usually give much thought to Numeric data types beyond whether we want to work with integers or decimal numbers. And that is a shame! In this post I’ll look at how we can actually do arithmetic operations lazily, and in the process hopefully reveal a bit about haskell’s numeric classes.


> module LazyArithmetic
>     where

We will be using Lennart Augustsson’s numbers library which can be installed from hackage with cabal-install:

$> cabal install numbers


> import Data.Number.Natural
> import Data.List(genericLength)

Consider two functions: the Prelude function sum and genericLength from the List library:


 genericLength :: (Num i) => [b] -> i
 sum :: (Num a) => [a] -> a

…two simple functions that have the potential to be very expensive, depending on the length of the list and the values of the elements.
Read the rest of this article »

No Comments

An alternative definition for Data.List.groupBy

10/02/2010

The function groupBy from haskell’s standard library is defined in terms of span, the effect being that the supplied predicate function is used to compare the first element of a group with successive elements.

This isn’t clear from the docs, and you might try to do this and wonder at the output you got:

*Main> groupBy (< =) [3,4,5,3,2,1,4,4,1,1,2,3,4,5,4,5,6,7]
[[3,4,5,3],[2],[1,4,4,1,1,2,3,4,5,4,5,6,7]]

Read the rest of this article »

3 Comments

The Definition of Data.List.group

6/02/2010

I’ve been thinking quite a bit lately about a category of functions that are always a bit awkward to define: they involve cases where we would like to traverse a recursive data structure and do something with the data that we have passed over but which is “gone now”.
Read the rest of this article »

No Comments