Function composition

hi,

I am learning haskell and I was playing a bit with function composition in the repl.
I am a bit puzzled with the result returned. Could someone explain to me why it returns -13 and not 13?

ghci> f1 = (((-) 1) . (+ 10) . ( + 5))
ghci> f1 (-1)
-13

in my head I do the following: -1 - 1 = -2 => -2 + 10 = 8 => 8 + 5 = 13

1 Like

(-) a b is the same as (a-b). Remembering that composition is read right-to-left:

(-1) + 5 => 4 + 10 => 1-14 => -13

If you want to subtract 1 from a number, you can use subtract

λ> subtract 1 98
97

We need subtract because in Haskell grammar, as you have discovered (-1) is not treated as a section (like (+19) 2) but as a negative number.

2 Likes

thank you so much for your clear explanation, it all makes sense now. but I feel like I’ll be making that mistake more than once …

1 Like

Since GHC 9.0, there is the really nice LexicalNegation extension, which makes everything in this area more intuitive, in particular, (- 1) is then parsed as an operator section, so this behaves as you would expect:

 Λ :set -XLexicalNegation
 Λ f1 = (- 1) . (+ 10) . ( + 5)
 Λ f1 -1
13
6 Likes

Good to know thanks! :slight_smile: