Dot in haskell, tricky example - haskell

I know that "haskells dot" question was answered couple times before on stackoverflow but I came across a example that shows me I still don't fully get it. Let's say I have functions
f :: Integer -> Integer
f x = x
g x = \y -> y
Now, as far as I know dot works like function composition -> f (g x) = (f . g) x
. So
(f . g) 4 5
shuld returns 5. Because g takes two arguments and returns second one, and f is simply identity. However it doesn't, Im getting Couldn't match type error. I have a feeling that haskell parses this expresion to something like ((f . g) 4) 5. But I need deeper explanation

As mentioned in the question, we have:
(f . g) x = f (g x)
Hence, in particular
(f . g) 4 = f (g 4) (*)
from which we have
(f . g) 4 5
= -- application associates to the left
((f . g) 4) 5
= -- equation (*) above
(f (g 4)) 5 =
= -- application associates to the left
f (g 4) 5
We can now see that the last argument 5 is being left as the second argument of f, and not passed to g.
It is useful to remember that Haskell functions are curried: technically, there's no such a thing as a function which takes two arguments. A function having type a -> b -> c is actually a unary function returning a unary function, even if we like to think of that as a binary function.
The composition operator works on unary functions as well: f . g composes the unary functions f and g. If f is "binary", it is treated as a unary function returning a function. This makes it take an additional argument, as shown above. If g is "binary", its returned function is passed to f.
So, using the above definitions:
f x = x
g x = \y -> y
we get:
(f . g) 4 5
= -- done above
f (g 4) 5
= -- associativity
(f (g 4)) 5
= -- definition of f
(g 4) 5
= -- definition of g
(\y -> y) 5
= -- beta reduction
5

main = print $(f . g) 4 5
f x = x
g x = \y -> y
Compiles nicely and when run prints 5. I'm using GHC 8.0.1.
Maybe you'd rather provide a complete minimal etc. example?

Related

How one parameter is used by two function simultaneously

I am reading about applicative functors and found such line:
(+) <$> (+3) <*> (*100) $ 5
It outputs 508.
How 5 could be used by (+3) and (*100) at the same time?
Why don't we need to pass two 5's as a parameters like:
(+) <$> (+3) <*> (*100) $ 5 5
In the (->) a applicative instance, we find:
instance Applicative ((->) a) where
pure = const
(<*>) f g x = f x (g x)
liftA2 q f g x = q (f x) (g x)
So, x is passed to both f and g by definition.
Here is a way to unbox it. We start with
e = ((+) <$> (+3)) <*> (*100)
(note that I left out the $ 5). The Applicative Functor whose <$> and <*> we are using here is the Function type (->) (partially applied to, I guess, Integer). Here, the meaning of <$> and <*> is as follows:
f <$> g = \y -> f (g y)
g <*> h = \x -> g x (h x)
We can plug that in into the term in the first line and get
e = \x -> (\y -> (+) ((+3) y)) x ((*100) x
There are a few simplifications that we can do to this term:
e = \x -> (x+3) + (x*100)
So if this function is the value of (+) <$> (+3) <*> (*100), then it should no longer be surprising that applying this to 5 gives
e 5 = (5+3) + (5*100) = 508
The thing is, you first have to understand how a function can be a functor. Think about a function like a container which reveals it's content only when you feed it with a parameter. In other words we only get to know it's content when this applicative functor (function) gets invoked with a parameter. So the type of this function would be say r -> a on two different types. However for functors we can only take an effect on a single type. So applicative functors are partially applied types just like the functor instance of Either type. We are interested in the output of the function so our applicative functor becomes (->) r in prefix notation. By remembering that <$> is the infix form of fmap
(+3) <$> (*2) $ 4 would result 11. 4 is applied to our functor (*2) and the result (which is the value in the applicative functor context) gets mapped with (+3).
However in our case we are fmaping (+) to (+3). To make it clearer lets rephrase the functions in lambda form.
(+) = \w x -> w + x and (+3) = \y -> y + 3.
then (+) <$> (+3) by partially applying \y -> y + 3 in the place of w our fmap applied applicative functor becomes \y x -> (y + 3) + x.
Now here comes the applicative operator <*>. As mentioned in previous answers it is of definition g <*> h = \x -> g x (h x) which takes a two parameter function g and partially applies g's second parameter with it's second parameter function h. Now our operation looks like
(\y x -> (y + 3) + x) <*> (*100) which can be rephrased as;
(\y x -> (y + 3) + x) <*> (\z -> z*100) which means now we have to partially apply \z -> z*100 to x and our function becomes \y z -> (y + 3) + (z*100).
Finally the applicative operator returns us a function which takes a single parameter and applies it to both parameters of the above two parameter function. So
\x -> (\y z -> (y + 3) + (z*100)) x x

Why does the dot compose from right to left in Haskell?

If we have two functions, f and g, then in Haskell h = f . g is equivalent to h x = f(g x). I.e. the functions are applied from right to left to the input. Is there any fundamental reason why it goes from right to left, and not from left to right? I.e. why didn't they make h = f . g equivalent to h x = g(f x) instead?
EDIT: as others pointed out my equivalent functions where the wrong way around, so I fixed those.
First of all, there's a mistake in your [original, unedited] question:
h = f . g is equivalent to h x = g(f x)
— that's not true: h = f . g is equivalent to h x = f (g x).
However, as to why it's that way and not the other way around, it's most likely because that's how it works and has worked in math; see http://en.wikipedia.org/wiki/Function_composition:
[...] composite function is denoted g ∘ f : X → Z, defined by (g ∘ f )(x) = g(f(x)) for all x in X.
It's also intuitive because of the equality (f . g) x == f (g x) — as you can see, the order of f and g is the same on both sides.
Moreover, it's trivial to create your own "reverse composition" operator if you desire one for reasons of e.g. readability:
(.>) = flip (.)
so that
Prelude> ((+1) .> (*2)) 3
8
Prelude> ((+1) . (*2)) 3
7
In fact, you can just use Control.Arrow.(>>>) which does the same for functions but is more general and works for other things as well:
Prelude Control.Arrow> ((+1) >>> (*2)) 3
8

Haskell - How to write (.) f f = (\x -> f (f x))

I need to write on a module to be run on GHCi, with a function composition to the same function. This (The classic fog(x) = f(g(x))) runs:
(.) f g = (\x -> f (g x)).
The problem appears when I try to write it like this
(.) f f = (\x -> f (f x)). (fof(x) = f(f(x)))
GHCi says:
"Conflicting definitions for `f'
Bound at: Lab1.hs:27:9
Lab1.hs:27:12"
Line 27:9 appear on the first time f and line 27:12 appear f again.
Why doesn't Haskell understand (.) f f = (\x -> f (f x))?
In Haskell, arguments to a function must have unique names. Using the same name for another argument is not allowed. This is because
foo x y = ... === foo = (\x-> (\y-> ...))
and if y where replaced with x, the second x would just shadow the first inside the ... body: there would be no way to reference the first x from there.
You can just define twice f x = f (f x):
Prelude> :t twice
twice :: (t -> t) -> t -> t
Prelude> twice (+1) 4
6
Alternatively, f (f x) = (.) f f x = join (.) f x:
Prelude Control.Monad> :t join (.)
join (.) :: (b -> b) -> b -> b
join is defined in Control.Monad. For functions, it holds that join g x = g x x. It is also known as W combinator.
E.g. print $ join (.) (+1) 4 prints 6.
As the error message says, you have conflicting definitions for f in the definition (.) f f = (\x -> f (f x)). You are binding the name f to both the first and second arguments to (.), so ghci doesn't know which argument to use when evaluating the expression f x.
There is nothing wrong with defining (.) using the pattern (.) f g, and then calling it with two arguments that happen to be the same.

simple Haskell functions in point-free style

I am trying to understand how to convert functions to point-free notation in Haskell. I saw this example, but it is more complicated than what I am looking for. I feel like I understand the logic behind it, but when I am trying to execute some simple examples in code I am getting compile errors. I want to try and write this function in point-free style:
f x = 5 + 8/x which I rearranged as f x = (+) 5 $ (/) 8 x
So, I thought it might be something like this:
f = (+) 5 $ (/) 8
but when I run this in ghci I get this message:
No instance for (Num (a0 -> a0))
arising from the literal `5' at Test.hs:3:9
Possible fix: add an instance declaration for (Num (a0 -> a0))
In the first argument of `(+)', namely `5'
In the first argument of `($)', namely `(+) 5'
In the expression: (+) 5 $ (/) 8
Failed, modules loaded: none.
I don't understand the "No instance for..." message. What do I need to do to write this function in point-free style?
$ has a very low precedence. So, f x = (+) 5 $ (/) 8 x actually means f x = (+) 5 $ ((/) 8 x). Instead, rewrite that as
f x = (+) 5 ( (/) 8 x)
f x = ((+) 5) ( ((/) 8) x)
f x = ((+) 5) . ( ((/) 8) ) x
f = ((+) 5) . ( (/) 8 )
f = (5+) . (8/)
The last expression makes sense: f is the composition of two operations, first divide 8 by what one has, and then add 5 to the result. Remember, g.h means "apply h, then apply g the the result of that".
Conversion from lambda-calculus (which Haskell is a variant of) terms to SKI terms (totally pointfree functions, using only const (K), id (I) and <*> (S)) can be done with the following simple rules:
\x -> x translates to id;
\x -> y without x occurring in y translates to const y;
\x -> f g translates to f' <*> g' where
f' is a translation of \x -> f and
g' is a translation of \x -> g.
Now you may wonder where does the . come in. There is a special case of the last translation: if f does not have any free occurrences of x, then \x -> f g translates to const f <*> (\x -> g), which is equal to f . (\x -> g).
Using those rules we can convert your function:
f = \x -> ((+) 5) (((/) 8) x) = -- by the special-case (.) rule
((+) 5) . (\x -> (((/) 8) x)) = -- by eta-reduction ((\x -> f x) = f)
((+) 5) . ((/) 8)
Eta-reduction is not necessary to complete the translation, but without it we'd get something messier. For example, the last step would yield ((+) 5) . ((/) 8) . id instead.
The "pointfree" program can be installed with cabal install pointfree, and shows you how to write an expression in pointfree style. For example:
$ pointfree "f x = 5 + 8/x"
f = (5 +) . (8 /)
Explanation of this conversion:
You can use "sections" for infix/operator functions. (a +) == \b -> a + b and (+ a) == \b -> b + a
The . function takes the result of the second parameter, which is a one-argument function, and applies it to the first argument.
You were really close. Allow me to add one more $ to illustrate:
f x = (+) 5 $ (/) 8 $ x
It should be clear that the expression (+) 5 is a function that takes one numeric input and produces a numeric output. The same goes for the expression (/) 8. So you take whatever number is input, x, and first apply the (/) 8 "function", and then apply the (+) 5 "function".
Whenever you have a chain of functions separated by $, you can replace all except the rightmost with . Meaning, if you have a $ b $ c $ d, this is equivalent to a . b . c $ d.
f x = (+) 5 . (/) 8 $ x
At this point, let's actually remove the $ and parenthesize instead.
f x = ((+) 5 . (/) 8) x
Now it should be clear that you can remove the trailing x from both sides:
f = (+) 5 . (/) 8
That is the main idea. If you have f x = expr x, you can "eta reduce" it to f = expr. In order to produce pointfree code, you need simply recognize how the larger function is composed of smaller functions. Partial application is sometimes necessary for point free code (as in this case, (+) 5 and (/) 8 are partially applied). The "pointfree" program is quite helpful for when you don't want to think about it; Lambdabot on the #haskell irc channel uses this program as a plugin, so you don't even have to install it yourself; just ask:
<DanBurton> #pl let f x = 5 + 8 / x in f
<lambdabot> (5 +) . (8 /)

What does a fullstop or period or dot (.) mean in Haskell?

I really wish that Google was better at searching for syntax:
decades :: (RealFrac a) => a -> a -> [a] -> Array Int Int
decades a b = hist (0,9) . map decade
where decade x = floor ((x - a) * s)
s = 10 / (b - a)
f(g(x))
is
in mathematics : f ∘ g (x)
in haskell : ( f . g ) (x)
It means function composition.
See this question.
Note also the f.g.h x is not equivalent to (f.g.h) x, because it is interpreted as f.g.(h x) which won't typecheck unless (h x) returns a function.
This is where the $ operator can come in handy: f.g.h $ x turns x from being a parameter to h to being a parameter to the whole expression. And so it becomes equivalent to f(g(h x)) and the pipe works again.
. is a higher order function for function composition.
Prelude> :type (.)
(.) :: (b -> c) -> (a -> b) -> a -> c
Prelude> (*2) . (+1) $ 1
4
Prelude> ((*2) . (+1)) 1
4
"The period is a function composition operator. In general terms, where f and g are functions, (f . g) x means the same as f (g x). In other words, the period is used to take the result from the function on the right, feed it as a parameter to the function on the left, and return a new function that represents this computation."
It is a function composition: link
Function composition (the page is pretty long, use search)

Resources