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

Ketil Malde ketil at malde.org
Mon Jun 16 04:19:16 EDT 2008


"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]

-k
-- 
If I haven't seen further, it is by standing in the footprints of giants


More information about the Haskell-Cafe mailing list