Subtraction behavior in a higher order function of Haskell

I am trying to write this function that applies function f to x twice

 Prelude> applyTwice :: (a -> a) -> a -> a Prelude> let applyTwice fx = f (fx) 

Now when I try to evaluate the expression below

 Prelude> applyTwice (`subtract` 3) 10 Output: 10 Prelude> applyTwice (3 `subtract`) 10 Output: 4 

According to my understanding, subtract is an infix function, so this parameter should fill in an empty position (left or right operand), and therefore, the first applyTwice (`subtract` 3) 10 expression should behave like

 10 `subtract` 3 `subtract` 3 

So, the result in this case should be 4 , but output 10

While in another case, i.e. applyTwice (3 `subtract`) 10 , output 4 , where I expect it to be 10

Am I mistaken somewhere?

+4
source share
1 answer

Your understanding of applyTwice and operator section notation is correct. However, you are probably confused about what subtract does. See library documentation for :

same as flip (-)

So subtract like (-) , but with arguments turned upside down. Hence,

  applyTwice (`subtract` 3) 10 = (`subtract` 3) ((`subtract` 3) 10) = (`subtract` 3) (10 `subtract` 3) = ((10 `subtract` 3) `subtract` 3) = (3 - 10) `subtract` 3 = (-7) `subtract` 3 = 3 - (-7) = 10 

And similarly for another expression.

+6
source

All Articles