5

I have a function (mergeall) that returns a float list. I want to calculate differences of every pair of adjacent elements in this list. For example:

[1.1,2.2,3.3,4.4,5.5,6.6]
do 1.1-2.2, 2.2-3.3,3.3-4.4...
return list of all difference

So, this should be pass into a list and return a list. The problems are:

  1. How can I use the list from "mergeall"?
  2. How can I do the algorithm above? Could somebody help me? Thanks!
Prateek
  • 2,377
  • 17
  • 29
SPG
  • 6,109
  • 14
  • 48
  • 79

2 Answers2

12
differences fs = zipWith (-) fs (tail fs)
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • 4
    Or the pointfree version: `differences = ap (zipWith (-)) tail` – Lily Ballard Dec 07 '11 at 00:47
  • Shouldn't you use `.` instead of `ap` since no lifting into a monad is involve? Also, `.` has a lower precedence than function application. – Jeff Burdges Dec 07 '11 at 01:09
  • 6
    @JeffBurdges Actually, some lifting is involved -- in particular, into the `(e ->)` monad. Function composition `(.)` doesn't quite cut it here, because the same argument is supplied twice in different places. – Daniel Wagner Dec 07 '11 at 01:12
  • 2
    @augustss: That's why I supplied it as a comment instead of as part of the answer proper. I find it interesting to see the pointfree versions of various functions, but they are often more obtuse. – Lily Ballard Dec 07 '11 at 01:14
  • 2
    Incidentally, if you want the opposite difference (e.g. `2.2-1.1`), the pointfree version would look like `zipWith (-) =<< tail` – Lily Ballard Dec 07 '11 at 01:16
  • 4
    Ahh, `ap = liftM2 ($)` here lifts function application to the second argument for its first argument `zipWith (-)` but doesn't mess with `tail` and the monad dictates that all functions apply to the same value. cute. :) – Jeff Burdges Dec 07 '11 at 01:48
  • 2
    @JeffBurdges: Yeah, it took me a while to wrap around how the `(e ->)` monad worked. I still find it faster to ask the [pointfree](http://hackage.haskell.org/package/pointfree) utility to generate these expressions for me, but at least now I can read them pretty easily. – Lily Ballard Dec 07 '11 at 02:11
  • 1
    @Kevin Ballard: Which is why `zipWith subtract =<< tail` gets you back to the "original" version. – BMeph Apr 17 '12 at 20:20
2

A pointfree solution using Control.Applicative:

differences = zipWith (-) <*> tail

Editor's note: I don't understand why this post is deleted by the owner. It's a good answer.

Redu
  • 25,060
  • 6
  • 56
  • 76
is7s
  • 3,500
  • 1
  • 20
  • 41