Where do the abstracts from this haskell function come from?

Let's say I have the following function:

sumAll :: [(Int,Int)] -> Int
sumAll xs = foldr (+) 0 (map f xs)
  where f (x,y) = x+y

The result sumAll [(1,1),(2,2),(3,3)]will be 12.

I don’t understand where the values ​​come from (x,y). Well, I know that they come from a variable xs, but I don’t understand how to do this. I mean, to do the code above directly without the where keyword, it would be something like this:

sumAll xs = foldr (+) 0 (map (\(x,y) -> x+y) xs)

And I can not understand, in the upper code as variables fand (x,y)are an expression of lambda (\(x,y) -> x+y).

+3
source share
3 answers

In Haskell, functions are first-class data types.

, , .

'f' , ( (x, y)) (x + y).

foldr - , 3 , ( +) (0) .

', f (x, y) = x + y' -

sumAll :: [(Int,Int)] -> Int
sumAll xs = foldr (+) 0 (map myFunctionF xs)

myFunctionF :: (Int,Int) -> Int
myFunctionF (x,y) = x + y

. , foldr, Haskell Reference Zvon foldl/map.

foldl :: (a -> b -> b) -> b -> [a] -> b
foldl _ x [] = x
foldl fx (y:ys) = foldl f (f y x) ys

map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = (f x) : (map f xs)
+5

, . , f , .

sumAll [(1,1),(2,2),(3,3)] 
      -- definition of sumAll
    = foldr (+) 0 (map f [(1,1),(2,2),(3,3)])
      -- application of map
    = foldr (+) 0 (f (1,1) : map f [(2,2),(3,3)])
      -- application of foldr
    = 0 + foldr (+) (f (1,1)) (map f [(2,2),(3,3)])
      -- application of map
    = 0 + foldr (+) (f (1,1)) (f (2,2) : map f [(3,3)])
      -- application of foldr
    = 0 + (f (1,1) + foldr (+) (f (2,2)) (map f [(3,3)]))
      -- application of f
    = 0 + (2 + foldr (+) (f (2,2)) (map f [(3,3)]))
      -- application of map
    = 0 + (2 + foldr (+) (f (2,2)) (f (3,3) : map f []))
      -- application of foldr
    = 0 + (2 + (f (2,2) + foldr (+) (f (3,3)) (map f [])))
      -- application of f
    = 0 + (2 + (4 + foldr (+) (f (3,3)) (map f [])))
      -- application of map
    = 0 + (2 + (4 + foldr (+) (f (3,3)) []))
      -- application of foldr
    = 0 + (2 + (4 + f (3,3)))
      -- application of f
    = 0 + (2 + (4 + 6))
    = 0 + (2 + 10)
    = 0 + 12
    = 12
+6

, , , f:

f (x, y) = x + y

f = uncurry (+)
+3

All Articles