Author | Message |
---|---|
rabbott
Posts: 1649
|
Posted 20:16 Oct 03, 2017 |
One of the most important features of functional programming is that it has no side effects. Consequently, if one expression is known to be equal to another they can be substituted for each other. Consider the following function, which is similar to some of the functions in Project 2. p = f . g . h As you all know by now this is expressed in point free form. It's important to realize that this is also a statement of the equality of two expressions. The expression p is equal to the expression f . g . h. An implication of that is that they can be substituted for each other. Assume we know that p is a function of one argument. That means that the function constructed by composing f and g and h is also a function of one argument. Therefore p x = (f . g . h) x. Why do you need the parentheses around f . g . h ? You need those parentheses for the same reason you need parentheses in (3 + 4) * 5, if that in fact is what you want to compute. What would happen if you left out the parentheses? You would get 3 + 4 * 5. But these two expressions are not the same. The first is equal to 35; the second is equal to 23. The issue is a matter of operator precedence. Without parentheses we perform * before +. It doesn't have to be that way. It's only a convention. But given that convention we need the parentheses. The same is true for (f . g . h) x. If you leave out the parentheses you get f . g . h x. Since function application has higher precedence than function composition, this means f . g . (h x). The problem is that h x may not even be a function. Consider a slightly simpler example: (sqrt . sin) 5. That means compose sqrt with sin and apply the result to 5. What is sqrt . sin? You should know that it is "the function of one argument that calls sin on that argument and then calls sqrt on the result." In Haskell terms that is written? \x -> sqrt (sin x). Since that lambda expression is the composition of sin and sqrt we can replace the composition with that expression: (\x -> sqrt (sin x)) 5. One can then apply that composed function to 5 (by replacing x with 5) and get: sqrt (sin x). We can then evaluate that expression to get a number. But what if instead we simply dropped the parentheses from (sqrt . sin) 5? We would have sqrt . sin 5. The only thing we can do with that is to apply sin to 5 and get a number. (It happens to be -0.96.) Then we would have sqrt . (-0.96). But now we're stuck. We can't compose the function sqrt with a number. So that's why the parentheses matter. |