0

I have a code

g :: Int->Int->Int
g x y = x*2 - y

then If i call foldl1 g [4,3,2,1] it returns 15, but i don't get how it returns 15, can anyone explain me why this is the case?

Han Ben
  • 17
  • 4
  • 1
    Meta question: Are you the author of [this now-deleted question](https://stackoverflow.com/q/49122630/2751851)? If so, I would suggest you repost the `foldPairs` part of it -- there were some rather interesting points to be made about it, and I was about to finish an answer covering them... – duplode Mar 06 '18 at 04:15
  • I was also mid-edit on an answer to your question when you deleted. – Marc Talbot Mar 06 '18 at 04:25

1 Answers1

4

foldl1 first applies the function to the first two elements of the list, then takes the result and applies the function to it and the third element, then takes the result and applies the function to it and the fourth element, then to result and fifth element, then sixth element, and so on until the list ends.

So:

Step 1:  g 4 3 = 4*2 - 3 = 5
Step 2:  g 5 2 = 5*2 - 2 = 8
Step 3:  g 8 1 = 8*2 - 1 = 15
Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • 3
    A useful identity (I think) is `foldl1 f (x:xs) == foldl f x xs` (`foldl f []` being undefined). – chepner Mar 06 '18 at 14:36
  • 2
    @chepner While that's a useful identity for an experienced programmer (or mathematician), I think it would be hardly helpful to the OP, judging their skill/knowledge level by their question. – Fyodor Soikin Mar 06 '18 at 15:42
  • 1
    I wasn't sure if the question was regarding the folding aspect, or `foldl1` specifically. – chepner Mar 06 '18 at 15:48
  • The way you have answered this makes it sound like it requires the list to have at least 2 elements, while it requires only 1. "Step 0" would be to take just the first element. – Peter Hall Aug 20 '21 at 01:20
  • True @PeterHall, that would be more correct. But I believe less educational. The question focused on a particular input, not on how the function works in general, and the OP was clearly very inexperienced. – Fyodor Soikin Aug 20 '21 at 02:36