foldl1 (\a b -> ((snd a) + (snd b...">

Haskell Error for "foldl1 (\ ab & # 8594; (snd a + snd b)) [(1,2), (3,4)]

Why is this not working?

Prelude> foldl1 (\a b -> ((snd a) + (snd b))) [(1,2),(3,4)]

<interactive>:1:17:
    Occurs check: cannot construct the infinite type: b = (a, b)
      Expected type: (a, b)
      Inferred type: b
    In the expression: ((snd a) + (snd b))
    In the first argument of `foldl1', namely
        `(\ a b -> ((snd a) + (snd b)))'
+3
source share
2 answers

foldl1The function argument must be of type a -> a -> a, that is, 2 input arguments and the return value must be of the same type. In your expression, this function is expected to return a 2-tuple Num b => (a, b), not a pure number Num b => b, so the check is in progress.

You can use foldland specify an initial value, for example.

foldl (\acc elm -> acc + snd elm) 0 [(1,2),(3,4)]

or use existing features

(sum . map snd) [(1,2),(3,4)]
+12
source

The function you provide foldl1should return a value of the same type as in your array.

(Number, Number), - Number.

, foldl, foldl1, (, KennyTM : D)

+2

Source: https://habr.com/ru/post/1779013/