Starting with Haskell - haskell

Can someone explain to me whats going on in this function?
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
I do understand what curried functions are, this could be re-written like this:
applyTwice :: ((a -> a) -> (a -> (a)))
applyTwice f x = f (f x)
However I dont fully understand the (+3) operator and how it works. Maybe it's something really stupid but I can't figure it out.
Can someone explain step by step how the function works? Thanks =)
applyTwice :: ((a -> a) -> (a -> (a)))
applyTwice f x = f (f x)

Haskell has "operator slicing": if you omit one or both of the arguments to an operator, Haskell automatically turns it into a function for you.
Specifically, (+3) is missing the first argument (Haskell has no unary +). So, Haskell makes that expression into a function that takes the missing argument, and returns the input value plus 3:
-- all the following functions are the same
f1 x = x + 3
f2 = (+3)
f3 = \ x -> x + 3
Similarly, if you omit both arguments, Haskell turns it into a function with two (curried) arguments:
-- all the following functions are the same
g1 x y = x + y
g2 = (+)
g3 = \ x y -> x + y
From comments: note that Haskell does have unary -. So, (-n) is not an operator slice, it just evaluates the negative (same as negate n).
If you want to slice binary - the way you do +, you can use (subtract n) instead:
-- all the following functions are the same
h1 x = x - 3
h2 = subtract 3
h3 = \ x -> x - 3

Related

How do you determine the way to write functions so that they are compatible for composing?

Let's say we have these 2 functions
f1 :: Int -> [Int] -> Int -> [Int]
f1 _ [] _ = []
f1 x (h:t) y = (x * h + y):(f1 x t y)
f2 :: [Int] -> Int
f2 (h:t) = h
Why does (f2 . f1 1 [1..10]) 1 work, but (f2 . f1 1) [1..10] 1 doesn't work?
All functions in Haskell take exactly one argument and return one value. The argument and/or the return type could be another function.
f1 has an argument type of Int and a return type of [Int] -> Int -> [Int]. The right associativity of (->) means we don't have to explicitly write this as
f1 :: Int -> ([Int] -> (Int -> [Int]))
but can instead drop the parentheses.
(Yes, (->) is an operator. You can use :k in GHCi to see the kind, but unfortunately what you get back is more complicated than we want to explain here:
> :k (->)
(->) :: TYPE q -> TYPE r -> *
Don't worry about what TYPE q and TYPE r stand for. Suffice it to say that (->) takes two types and returns a new type, and we can assume a simpler kind like
(->) :: * -> * -> *
The kind * is the kind of an ordinary type, more frequently written as Type these days.
)
In order to compose two functions, the return type of one must match the argument type of the other. We can see this from the type of (.) itself:
(.) :: (b -> c) -> (a -> b) -> a -> c
^ ^
That's not the case with f1 and f2:
-- vvvvvvvvvvvvvvvvvvvvv
f1 :: Int -> ([Int] -> Int -> [Int])
f2 :: [Int] -> Int
-- ^^^^^
-- [Int] -> Int -> [Int] and [Int] are different types
nor with f1 1 and f2
-- vvvvvvvvvvvv
f1 1 :: [Int] -> (Int -> [Int])
f2 :: [Int] -> Int
-- ^^^^^
-- Int -> [Int] and [Int] are different types
but it is true of f1 1 [1..10] and f2:
-- vvvvv
f1 1 [1..10] :: Int -> [Int]
f2 :: [Int] -> Int
-- ^^^^^
-- [Int] and [Int] are the same type
While (->) is right-associative, function application is left-associative, which is why we can write
((f1 1) [1..10]) 1
as f1 1 [1..10] 1 instead, leading to the appearance of f1 as taking 3 arguments, rather than an expression involving 3 separate function calls. You can see the three calls more clearly if you use a let expression to name each intermediate function explicitly:
let t1 = f1 1
t2 = t1 [1..10]
t3 = t2 1
in t3
As a complement to chepner's excellent answer, here's a less formal way of looking at it (which might be more intuitive if you haven't assimilated the formalities yet).
You seem to be thinking of (f . g) arg as a special syntactic form that will pass the argument to g and then call f on the result1. In fact this isn't what happens (or at best it's a shorthand for what happens).
Remember that functions are first class in Haskell. Frequently when that is brought up it means that we are passing functions as values to other functions, or storing them in data structures. But here what we need to remember is that first-class values can be computed as the result of expressions. f . g is an expression that computes a new function, in precisely the same manner that 7 + 9 is an expression that computes a new integer.
So (f . g) arg is not passing arg to g. It's passing arg to the function that is computed by the expression f . g. And if we had multiple arguments where arg is written, as in (f . g) x y z they would all be passed to the whole function f . g. There is no way for any of them to be passed to g directly.
The . operator builds a new function out of f and g by producing a function that behaves as follows: it takes a single argument x, passes it to g and then passes the result of that to f. In Haskell syntax that is basically (f . g) x = f (g x)2. So if we try to pass multiple arguments, as in (f . g) x y z, we end up with this:
(f . g) x y z = (f (g x)) y z
You can see this doesn't end up passing more arguments to g before g's result is fed to f; rather y and z end up being passed to the final result after x has been fed all the way through g and f (this is only going to work if f itself returns a function after being applied to one argument3). A simple way to think of it is that the first argument to the composed function "flows through the composition pipeline"; any other arguments will be passed to the result, after x has "flowed through". If we wanted the extra arguments to be passed to g, we should write it this way:
(f . g x y) z = f (g x y z)
Note that this reframes the "flow"; now it's z that is feeding through the composed functions. x and y have moved to being part of the definition of one of the two composed functions (g x y is every bit as much of an "expression that computes a function" as f . g is). If you really want the emphasis to be on x "flowing through" the composition pipeline, you'll need to change the way you defined g so that it takes arguments in a different order. This is a big part of why Haskellers frequently write functions to take the "main thing being operated on" as their last argument.
With all that in mind, your question should be pretty clear now.
In (f2 . f1 1 [1..10]) 1 the outermost 1 will "flow through the pipeline"; the first stage of the pipeline is f1 1 [1..10] (so the 1 will end up as a third argument to f1).
Whereas in (f2 . f1 1) [1..10] 1, the [1..10] will "flow through the pipeline", and the outer 1 will only be passed to the final result of the whole pipeline, not to the first stage of the pipeline. And the final result of the composition pipeline is the result of f2, which is a simple Int and cannot be applied to more arguments.
1 Haskell does have syntax for "pass multiple arguments to one function, then call another function on the result of that". However it's much more pedestrian. Just write f (g x y z). If this looks simpler to you than trying to twist it into a chain of function compositions, then just write it directly.
2 (f . g) x = f (g x) is almost the literal definition of the . operator. The real definition is f . g = \x -> f (g x). This definition is equivalent in the sense that it always produces exactly the same result, but it is usually a bit more efficient.
3 And your f2 example does not return a function after being applied to one argument (it just returns an Int), so we can see that (f2 . _anything_) arg1 arg2 is definitely going to be a type error with no further analysis, no matter what other function you're composing or what the two arguments are.

Too many arguments for fmap

The first argument, that fmap is expected is a function with one argument.
fmap :: Functor f => (a -> b) -> f a -> f b
Then I tried as follow in prelude:
Prelude> x = fmap (\x y -> x * y)
As you can see, the first argument to fmap is a function, that has two arguments. Why does the compiler let it pass?
The function that I pass to fmap above has two arguments not one!
Haskell does not actually have functions with more (or less) than one argument. A "two-argument function" is really just a function that takes one argument and produces another function that takes another argument. That is, \x y -> x * y is just a syntactic short cut for \x -> \y -> x * y. This concept is known as currying.
So this should explain what's happening in your example. Your fmap will simply turn an f of numbers into an f of functions. So, for example, x [1,2,3] would produce the list [\y -> 1 * y, \y -> 2 * y, \y -> 3 * y] (a.k.a. [(1*), (2*), (3*)]).
You have defined a function. One of the fundamental aspects of functional programming that functions can be parameters, stored into variables, etc.
If we then query the type of x, we get:
Prelude> :t x
x :: (Functor f, Num a) => f a -> f (a -> a)
So x is now a function that takes as input a Functor with a applied on that function, and returns the an element of a type with the same functor, but applied with a -> a.
So you can for instance apply a list on x, like:
Prelude> :t x [1,4,2,5]
x [1,4,2,5] :: Num a => [a -> a]
So now we have a list of functions, that is equivalent to:
[\x -> 1*x, \x -> 4*x, \x -> 2*x, \x -> 5*x]

Haskell Fold with anonymous function

I have a problem with one of the Haskell basics: Fold + anonymous functions
I'm developing a bin2dec program with foldl.
The solution looks like this:
bin2dec :: String -> Int
bin2dec = foldl (\x y -> if y=='1' then x*2 + 1 else x*2) 0
I understand the basic idea of foldl / foldr but I can't understand what the parameters x y stands for.
See the type of foldl
foldl :: (a -> b -> a) -> a -> [b] -> a
Consider foldl f z list
so foldl basically works incrementally on the list (or anything foldable), taking 1 element from the left and applying f z element to get the new element to be used for the next step while folding over the rest of the elements. Basically a trivial definition of foldl might help understanding it.
foldl f z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
The diagram from Haskell wiki might help building a better intuition.
Consider your function f = (\x y -> if y=='1' then x*2 + 1 else x*2) and try to write the trace for foldl f 0 "11". Here "11" is same as ['1','1']
foldl f 0 ['1','1']
= foldl f (f 0 '1') ['1']
Now f is a function which takes 2 arguments, first a integer and second a character and returns a integer.
So In this case x=0 and y='1', so f x y = 0*2 + 1 = 1
= foldl f 1 ['1']
= foldl f (f 1 '1') []
Now again applying f 1 '1'. Here x=1 and y='1' so f x y = 1*2 + 1 = 3.
= foldl f 3 []
Using the first definition of foldl for empty list.
= 3
Which is the decimal representation of "11".
Use the types! You can type :t in GHCi followed by any function or value to see its type. Here's what happens if we ask the for the type of foldl
Prelude> :t foldl
foldl :: (a -> b -> a) -> a -> [b] -> a
The input list is of type [b], so it's a list of bs. The output type is a, which is what we're going to produce. You also have to supply an initial value for the fold, also of type a. The function is of type
a -> b -> a
The first parameter (a) is the value of the fold computed so far. The second parameter (b) is the next element of the list. So in your example
\x y -> if y == '1' then x * 2 + 1 else x * 2
the parameter x is the binary number you've computed so far, and y is the next character in the list (either a '1' or a '0').

Why is the type of this function (a -> a) -> a?

Why is the type of this function (a -> a) -> a?
Prelude> let y f = f (y f)
Prelude> :t y
y :: (t -> t) -> t
Shouldn't it be an infinite/recursive type?
I was going to try and put into words what I think it's type should be, but I just can't do it for some reason.
y :: (t -> t) -> ?WTFIsGoingOnOnTheRHS?
I don't get how f (y f) resolves to a value. The following makes a little more sense to me:
Prelude> let y f x = f (y f) x
Prelude> :t y
y :: ((a -> b) -> a -> b) -> a -> b
But it's still ridiculously confusing. What's going on?
Well, y has to be of type (a -> b) -> c, for some a, b and c we don't know yet; after all, it takes a function, f, and applies it to an argument, so it must be a function taking a function.
Since y f = f x (again, for some x), we know that the return type of y must be the return type of f itself. So, we can refine the type of y a bit: it must be (a -> b) -> b for some a and b we don't know yet.
To figure out what a is, we just have to look at the type of the value passed to f. It's y f, which is the expression we're trying to figure out the type of right now. We're saying that the type of y is (a -> b) -> b (for some a, b, etc.), so we can say that this application of y f must be of type b itself.
So, the type of the argument to f is b. Put it all back together, and we get (b -> b) -> b — which is, of course, the same thing as (a -> a) -> a.
Here's a more intuitive, but less precise view of things: we're saying that y f = f (y f), which we can expand to the equivalent y f = f (f (y f)), y f = f (f (f (y f))), and so on. So, we know that we can always apply another f around the whole thing, and since the "whole thing" in question is the result of applying f to an argument, f has to have the type a -> a; and since we just concluded that the whole thing is the result of applying f to an argument, the return type of y must be that of f itself — coming together, again, as (a -> a) -> a.
Just two points to add to other people's answers.
The function you're defining is usually called fix, and it is a fixed-point combinator: a function that computes the fixed point of another function. In mathematics, the fixed point of a function f is an argument x such that f x = x. This already allows you to infer that the type of fix has to be (a -> a) -> a; "function that takes a function from a to a, and returns an a."
You've called your function y, which seems to be after the Y combinator, but this is an inaccurate name: the Y combinator is one specific fixed point combinator, but not the same as the one you've defined here.
I don't get how f (y f) resolves to a value.
Well, the trick is that Haskell is a non-strict (a.k.a. "lazy") language. The calculation of f (y f) can terminate if f doesn't need to evaluate its y f argument in all cases. So, if you're defining factorial (as John L illustrates), fac (y fac) 1 evaluates to 1 without evaluating y fac.
Strict languages can't do this, so in those languages you cannot define a fixed-point combinator in this way. In those languages, the textbook fixed-point combinator is the Y combinator proper.
#ehird's done a good job of explaining the type, so I'd like to show how it can resolve to a value with some examples.
f1 :: Int -> Int
f1 _ = 5
-- expansion of y applied to f1
y f1
f1 (y f1) -- definition of y
5 -- definition of f1 (the argument is ignored)
-- here's an example that uses the argument, a factorial function
fac :: (Int -> Int) -> (Int -> Int)
fac next 1 = 1
fac next n = n * next (n-1)
y fac :: Int -> Int
fac (y fac) -- def. of y
-- at this point, further evaluation requires the next argument
-- so let's try 3
fac (y fac) 3 :: Int
3 * (y fac) 2 -- def. of fac
3 * (fac (y fac) 2) -- def. of y
3 * (2 * (y fac) 1) -- def. of fac
3 * (2 * (fac (y fac) 1) -- def. of y
3 * (2 * 1) -- def. of fac
You can follow the same steps with any function you like to see what will happen. Both of these examples converge to values, but that doesn't always happen.
Let me tell about a combinator. It's called the "fixpoint combinator" and it has the following property:
The Property: the "fixpoint combinator" takes a function f :: (a -> a) and discovers a "fixed point" x :: a of that function such that f x == x. Some implementations of the fixpoint combinator might be better or worse at "discovering", but assuming it terminates, it will produce a fixed point of the input function. Any function that satisfies The Property can be called a "fixpoint combinator".
Call this "fixpoint combinator" y. Based on what we just said, the following are true:
-- as we said, y's input is f :: a -> a, and its output is x :: a, therefore
y :: (a -> a) -> a
-- let x be the fixed point discovered by applying f to y
y f == x -- because y discovers x, a fixed point of f, per The Property
f x == x -- the behavior of a fixed point, per The Property
-- now, per substitution of "x" with "f x" in "y f == x"
y f == f x
-- again, per substitution of "x" with "y f" in the previous line
y f == f (y f)
So there you go. You have defined y in terms of the essential property of the fixpoint combinator:
y f == f (y f). Instead of assuming that y f discovers x, you can assume that x represents a divergent computation, and still come to the same conclusion (iinm).
Since your function satisfies The Property, we can conclude that it is a fixpoint combinator, and that the other properties we have stated, including the type, are applicable to your function.
This isn't exactly a solid proof, but I hope it provides additional insight.

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