[Haskell-cafe] How to do this in FP way?

Michał Pałka michal.palka at poczta.fm
Mon Jun 16 06:48:38 EDT 2008


On Mon, 2008-06-16 at 10:19 +0200, Ketil Malde wrote:
> "Magicloud Magiclouds" <magicloud.magiclouds at gmail.com> writes:
> 
> > static int old;
> > int diff (int now) { /* this would be called once a second */
> >   int ret = now - old;
> >   old = now;
> >   return ret;
> > }
> 
> >     Because there is no "variable" in Haskell. So how to do this in a FP way?
> 
> I would claim the FP way is like this:
> 
>   -- | Repeatedly subtract values from a baseline, returning a list
>   --   containing each intermediate result
>   diff :: Int -> [Int] -> [Int]
>   diff = scanl (-)
> 
>   Prelude> diff 100 [1..10]
>   [100,99,97,94,90,85,79,72,64,55,45]

Better yet, you could create a recursive type that reflects what you are
actually doing:
newtype Step a = Step (a -> (a, Step a))

diff' :: Int -> Step Int
diff' x = Step (\a -> let r = a - x in (r, diff' r))

This way it will be easier to resume previous diff computations.

Best,
Michał



More information about the Haskell-Cafe mailing list