Understanding the function of composition with negation

After reading a page with higher-order functions from an amazing site , itโ€™s still hard for me to understand the negation function in combination with the composition of the functions.

to be more specific, take this piece of code:

ghci> map (negate . sum . tail) [[1..5],[3..6],[1..7]] 

which gives:

 [-14,-15,-27] 

I am rereading the page again, but to be honest, I still donโ€™t know how this line of code produced this answer, if someone could get me through this process, I would really appreciate it!

+4
source share
2 answers
 map f [a,b,c] = [fa, fb, fc] 

because map f (x:xs) = fx:map f xs - apply f to each element of the list.

So,

 map (negate.sum.tail) [[1..5],[3..6],[1..7]] = [(negate.sum.tail) [1..5], (negate.sum.tail) [3..6], (negate.sum.tail) [1..7]] 

now

 (negate . sum . tail) [1..5] = negate (sum (tail [1,2,3,4,5])) = negate (sum [2,3,4,5]) = negate 14 = -14 

because (fg) x = f (gx) and . are correct associative, therefore (negate.sum.tail) xs = (negate.(sum.tail)) xs , which, in turn, negate ((sum.tail) xs) = negate (sum (tail xs)) .

tail provides everything except the first element of the list: tail (x:xs) = xs , for example tail "Hello" = "ello" sum adds them, as you expect, and negate x = -x .

Others work similarly, giving minus the sum of the tail of each list.

+15
source

To add a different perspective to AndrewC's excellent answer, I usually think of these types of problems in terms of law factors and fmap . Since map can be considered as a specialization of fmap for lists, we can replace map with a more general fmap and maintain the same functionality:

 ghci> fmap (negate . sum . tail) [[1..5],[3..6],[1..7]] 

Now we can apply the law of compositional functor, using algebraic substitution, so that the shift in which the composition occurs, and then each function is individually listed according to the list:

 fmap (f . g) == fmap f . fmap g -- Composition functor law fmap (negate . sum . tail) $ [[1..5],[3..6],[1..7]] == fmap negate . fmap (sum . tail) $ [[1..5],[3..6],[1..7]] == fmap negate . fmap sum . fmap tail $ [[1..5],[3..6],[1..7]] == fmap negate . fmap sum $ fmap tail [[1..5],[3..6],[1..7]] == fmap negate . fmap sum $ [tail [1..5],tail [3..6],tail [1..7]] -- As per AndrewC explanation == fmap negate . fmap sum $ [[2..5],[4..6],[2..7]] == fmap negate $ [14, 15, 27] == [-14, -15, -27] 
+5
source

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


All Articles