"chain" the addition operator into a function that accepts 3 arguments? - function

I'd like to compose the addition operator (+) to make a function of this type:
Num a => a -> a -> a -> a
Like, the equivalent of this:
(\a b c -> a + b + c)
but without having to resort to lambdas.
I tried already
((+) . (+))
which I would have expected to work but surprisingly didn't.

http://pointfree.io gives the point-free version of \a b c -> a + b + c as ((+) .) . (+).
Informally, composition only works "intuitively" for first-order functions, which neither take functions as arguments nor return functions as values. (+) is a higher-order function; it takes a value of type Num a => a, and returns a function of type Num a => a -> a. When you try to compose higher-order functions in a naive fashion, the result is not what you expect:
:t (+) . (+)
(+) . (+) :: (Num a, Num (a -> a)) => a -> (a -> a) -> a -> a
Consider the definitions of the two functions:
(+) :: Num z => z -> z -> z
(.) :: (b -> c) -> (a -> b) -> (a -> c)
f . g = \x -> f (g x)
Then
(+) . (+) == (.) (+) (+)
== \x -> (+) ((+) x)
Because of currying, you wind up passing a function, not a number, as the first argument of the first (+).
So how do we get from h a b c = a + b + c to h = ((+) .) . (+)? Start by rewriting the infix expression as a prefix expression, using the fact that (+) is left-associative.
\a b c -> a + b + c
== \a b c -> ((+) a b ) + c
== \a b c -> (+) ((+) a b) c
Next, we alternately apply eta conversion to eliminate an argument and composition to move an argument into position to be eliminated. I've tried to be very explicit about identifying the functions use for the application of composition.
== \a b -> (+) ((+) a b) -- eta conversion to eliminate c
== \a b -> (+) (((+) a) b) -- parentheses justified by currying
-- f g -- f = (+), g = ((+) a)
-- \a b -> f ( g b)
-- \a b -> (f . g) b -- definition of (.)
== \a b -> ((+) . ((+) a)) b
== \a -> (+) . ((+) a) -- eta conversion to eliminate b
== \a -> (.) (+) ((+) a) -- prefix notation
== \a -> ((.) (+)) ((+) a) -- parentheses justified by currying
== \a -> ((+) . )((+) a) -- back to a section of (.)
-- f g -- f = ((+) .), g = (+)
-- \a -> f (g a)
-- \a -> ( f . g) a -- definition of (.)
== \a -> (((+) .) . (+)) a
== ((+) .) . (+) -- eta conversion to eliminate a

You need this strange operator (.).(.), which is sometimes defines as .: (think of 3 dots ...)
In ghci
Prelude> let (.:) = (.).(.)
Prelude> let f = (+) .: (+)
Prelude> f 1 2 3
> 6
Note this operator can also be defined as <$$> = fmap . fmap.

Although this introduces some noise, you could use uncurry :: (a -> b -> c) -> (a,b) -> c and curry :: ((a,b) -> c) -> a -> b -> c to temporary store the arguments of the second plus in one tuple:
curry $ (+) . uncurry (+) :: Num a => a -> a -> a -> a
or perhaps more semantically readable:
curry ((+) . uncurry (+)) :: Num a => a -> a -> a -> a
uncurry thus takes a function (here (+)) and transforms it into a function: uncurry (+) :: Num a => (a,a) -> a. So as a result you have transformed the (+) into a function that takes a tuple.
Now we can use (.) to make a composition with the first (+):
(+) . uncurry (+) :: Num a => (a,a) -> (a -> a)
So now we have a function that takes one argument (the tuple (a,a)) and produces a function that takes an a (the second operand of the first (+)) and calculates the sum. The problem is of course that we want to get rid of the tuple. We can do so by passing the function into a curry. That transforms the tuple-function ((a,a) -> (a -> a)) into a function taking the arguments separately (a -> (a -> (a -> a))).

Note the signature of the function composition operator:
(.) :: (b -> c) -> (a -> b) -> a -> c
^ ^ ^
Functions
It takes 2 functions, each which take 1 argument, and returns a function that takes an argument of the same type as the second function, and returns the same type as the first.
Your attempt to compose two +s didn't work since + takes 2 arguments, so without some hackish/creative workaround, this isn't possible.
At this point, I'd say forcing composition when it doesn't fit the problem is just going to make your life more difficult.
If you want to sum up multiple numbers, you could write a function like:
sum :: [Int] -> Int
sum nums = foldl (+) 0 nums
Or, since nums appears at the back of the definition, it can be dropped altogether, yielding a "point-free" form:
sum :: [Int] -> Int
sum = foldl (+) 0
It reduces/folds + over a list of numbers. If you haven't used folds yet, look into them now. They are one of the main ways to achieve looping in Haskell. It's essentially "implicit recursion" when you're dealing with lists, or anything else iterable.
With the above function defined, you can use it like:
sum [1, 2 3, 4, 5]

Related

currying in haskell when the uncurried form is known

I've been learning currying in Haskell and now trying to write the Haskell type signature of a function in curried form, whose uncurried form has an argument pair of type (x, y) and a value of type x as its result. I think the correct approach would be f :: (y,x) -> x, but I'm not sure. Is it correct, and if not, why?
You can let ghci do this for you.
> f = undefined :: (a, b) -> c
> :t curry f
curry f :: a -> b -> c
You can uncurry the result to get back the original type.
> :t uncurry (curry f)
uncurry (curry f) :: (a, b) -> c
The actual implementation of curry is, perhaps, more enlightening.
curry :: ((a, b) -> c) -> a -> b -> c
curry f = \x -> \y -> f (x, y)
If f expects a tuple, then curry f simply packages its two arguments into a tuple to pass to f.
Examples are hard to come by, as functions in Haskell are usually fully curried already. But we can explicitly uncurry a binary operator to construct an example.
> (+) 3 5
8
> f = uncurry (+)
> f (3, 5)
8
> (curry f) 3 5
8
As an aside, the type you suggested is what you would get by inserting a call to flip between currying and uncurrying a function:
> :t uncurry . flip . curry
uncurry . flip . curry :: ((b, a) -> c) -> (a, b) -> c
To see this in action, you'd have to pick a non-commutative operator, like (++).
> strconcat = uncurry (++)
> strconcat ("foo", "bar")
"foobar"
> (uncurry . flip . curry) strconcat ("foo", "bar")
"barfoo"
Just swapping the elements of the tuple is not currying. You have to get rid of the tuple altogether. You can do that by taking the first element of the tuple as argument and returning a function which takes the second element of the tuple and finally returns the result type. In your case the type would be f :: x -> (y -> x), these parenthesis are redundant, it is the same as f :: x -> y -> x. This is the curried form.

How to Implement functions from type signatures?

I have the following two type signatures in Haskell:
foo :: (a -> (a,b)) -> a -> [b]
bar :: (a -> b) -> (a -> b -> c) -> a -> c
I want to write a concrete implementation of these two functions but I'm really struggling to understand where to start.
I understand that foo takes a function (a -> (a,b)) and returns a and a list containing b.
And bar takes a function (b -> c) which returns a function (a -> b -> c) which finally returns a and c.
Can anyone show me an example of a concrete implementation?
How do I know where to start with something like this and what goes on the left side of the definition?
You have some misunderstandings there:
I understand that foo takes a function (a -> (a,b)) and returns a and a list containing b.
No, it doesn't return a. It expects it as another argument, in addition to that function.
And bar takes a function (b -> c) which returns a function (a -> b -> c) which finally returns a and c.
Same here. Given g :: a -> b, bar returns a function bar g :: (a -> b -> c) -> a -> c. This function, in turn, given a function h :: (a -> b -> c), returns a function of type a -> c. And so it goes.
It's just like playing with pieces of a puzzle:
foo :: (a -> (a,b)) -> a -> [b]
-- g :: a -> (a,b)
-- x :: a
-- g x :: (a,b)
foo g x = [b] where
(a,b) = g x
bar :: (a -> b) -> (a -> b -> c) -> a -> c
-- g :: a -> b
-- x :: a
-- g x :: b
-- h :: a -> b -> c
-- h x :: b -> c
-- h x (g x) :: c
bar g h x = c where
c = ....
There's not much free choice for us here. Although, there are more ways to get more values of type b, for foo. Instead of ignoring that a in (a,b) = g x, we can use it in more applications of g, so there actually are many more possibilities there, like
foo2 :: (a -> (a,b)) -> a -> [b]
foo2 g x = [b1,b2] where
(a1,b1) = g x
(a2,b2) = g a1
and many more. Still, the types guide the possible implementations. foo can even make use of foo in its implementation, according to the types:
foo3 :: (a -> (a,b)) -> a -> [b]
foo3 g x = b : bs where
(a,b) = g x
bs = ...
So now, with this implementation, the previous two become its special cases: foo g x === take 1 (foo3 g x) and foo2 g x === take 2 (foo3 g x). Having the most general definition is probably best.
In addition to #will-nes's answer, it will be useful to treat (->) as a right-associative infix operator. So something like f: a -> b -> c is the same as f: a -> (b -> c). So this is saying f is a function that takes a value of type a and returns you a value of type b -> c, which is, another function, one that takes a value of type b and returns you a value of type c.
So the types in your example can be re-written as follows
foo :: (a -> (a,b)) -> (a -> [b])
bar :: (a -> b) -> ((a -> (b -> c)) -> (a -> c))
Similarly, you can think of arguments to a function in pieces as well, as being left-associative (like + and -), though there's no explicit operator in this case. foo a b c d e is the same as ((((foo a) b) c) d) e. For example, let's say we have a function f: Int -> Int -> Int (which is the same as f: Int -> (Int -> Int)). You don't have to provide both arguments at once. So you can write g = f 1, which has the type (Int -> Int). And then you can provide an argument to g, like g 2, which has the type Int. f 1 2 and let g = f 1 in g 2 are more or less the same. Here's a more concrete example of how this works:
Prelude> f = (+)
Prelude> g = f 1
Prelude> g 2
3
Prelude> :t f
f :: Num a => a -> a -> a
Prelude> :t g
g :: Num a => a -> a
Prelude> :t g 2
g 2 :: Num a => a
In #will-nes's sample implementation examples, he defines the functions with all of the arguments up front, but you don't have to think of them that way. Just think of f: a -> b -> c as taking a value of type a and returning another function. While most of the methods you encounter will use all of their arguments up-front, there might be cases in which you don't want to do that. Here's an example:
veryExpensive :: A -> B
unstagedFun :: A -> (B -> C) -> C
unstagedFun a f = f (veryExpensive a)
stagedFun :: A -> (B -> C) -> C
stagedFun a = let b = veryExpensive a in \f -> f b
(You can also rewrite the latter as let b = veryExpensive a in ($ b))
Of course, with compiler optimizations, I wouldn't be surprised if the unstaged version staged automatically, but hopefully this offers some motivation for thinking of functions as not having multiple arguments, but rather, as a single argument, but they may return other functions that may themselves return functions (but also only take a single argument).

Use of function application operator in Haskell

What does the following expression means in haskell?
($ 3)
ghci shows the following type
($ 3) :: Num a => (a -> b) -> b.
($ 3) is a section, and is equivalent to \f -> f 3, which takes a function argument and applies it to 3.
If we considered 3 to be an integer, we would have that the type of f is Int -> b (for any b), so the type of ($ 3) would be (Int -> b) -> b.
Things in Haskell are a bit more complex, since 3 can be of any numeric type, so we don't really need f :: Int -> b, it's enough if f :: a -> b where a is a numeric type.
Hence we get ($ 3) :: Num a => (a -> b) -> b.
(# x) for any operator # is equivalent to \a -> a # x; so ($ 3) is equivalent to \f -> f $ 3, i.e. a function that applies any function you pass it to 3. This syntax is called "sections".
> let f = ($ 3)
> f show
"3"
> f square
9
Another way to look at it is
($) :: (a -> b) -> a -> b
3 :: Num a => a
and when you "insert 3" in the ($) it will become
($ 3) :: Num a => (a -> b) -> b.
due to that you no longer need to supply the a, but the function you need to supply is now restricted to num, since the 3 can be any numeric type.
This is at least how I look at functions in Haskell, like substitution in algebra.

Haskell. Functions in Num expressions

I start to learn Haskell. While studying a tutorial I have found the following example that enables the usage of functions in arithmetic expressions:
module FunNat where
instance Num a => Num (t -> a) where
(+) = fun2 (+)
(*) = fun2 (*)
(-) = fun2 (-)
abs = fun1 abs
signum = fun1 signum
fromInteger = const . fromInteger
fun1 :: (a -> b) -> ((t -> a) -> (t -> b))
fun1 = (.)
fun2 :: (a -> b -> c) -> ((t -> a) -> (t -> b) -> (t -> c))
fun2 op a b = \t -> a t `op` b t
The example works. But I can not understand how the (+) function is transformed into the function of two arguments. As I can understand each (+) is substituted with fun2 (+). And fun2 is equivalent to the function of one argument \t -> a t 'op' b t, but we should have a function of two arguments (something like (\t1 t2 -> (\x -> x ) t1 + (\x -> x) t2) ). I think that here some basic concepts of Haskell typing should be applied but I do not know what they are.
EDIT 1
I understand that fun2 is a function of three arguments. I can't understand internal expression transformation. I'm reasoning in the following way: (+) 3 4 = (+) (\x->3) (\x->4) = fun2 (+) (\x->3) (\x->4) = \t -> (\x->3) t + (\x->4) t
What is this t? Or where am I wrong in my reasoning? May be it is necessary to think another way?
EDIT 2
I think that I have reached some understanding of the issue (thanks you all!). So:
When we write (+) 3 4 - in this case a simple operation from Num is used, no special features from FunNat. To use (+) from FunNat it is necessary to write fun2 (+) 3 4 or fun2 (+) (\x -> 3) (\x -> 4). But these expressions expect any third parameter to be evaluated;
To demonstrate specific features from FunNat we may use the following example ((*)-(+)) (taken from tutorial) or in other form - (-) (*) (+). Both expressions take two arguments. In this case we have: ((*)-(+)) = fun2 (-) (*) (+) = \t -> (*) t - (+) t = \t -> (\t1 t2 -> t1 * t2) t - (\t1 t2 -> t1 + t2) t = (\t t2 -> t * t2) - (\t t2 -> t + t2) = \t t2 -> (t * t2) - (t + t2). The final expression expects just Num. I hope that all these are correct
As it was explained in tutorial, but I can't understand what for, the possibility to use (*) and (+) as parameters for fun2 that expects (t->a) is based on the following (taken from tutorial): t1 -> t2 -> a = t1->a' where a' = t2 -> a. Here curring is used.
So all necessary facts were on the surface but I do not take into consideration the non-trivial mechanism of type inference.
The type of (+) is Num a => a -> a -> a. Since you're creating an instance of Num for the type Num a => t -> a, consider the explicit signature
(+) :: Num a => (t -> a) -> (t -> a) -> (t -> a) (1)
or equivalently (by currying)
(+) :: Num a => (t -> a) -> (t -> a) -> t -> a (2)
What this says is: "If you give me 2 strategies for producing a Num a => a from a t, I can create a new strategy for producing a Num a => a from a t by using the Num.(+) instance of the a's"
I think the part that has you confused is that this specific (+) can be viewed as a function of 2 arguments which returns a function (1), or a function of 3 arguments which returns a value (2). Since functions in Haskell are curried, these are really the same thing.
In type signatures parentheses associate to the right, so:
f :: a -> (b -> c -> d)
is the same as:
f :: a -> b -> c -> d
So the parens indicated below are redundant:
fun2 :: (a -> b -> c) -> ((t -> a) -> (t -> b) -> (t -> c))
^ ^
and removing them leaves:
fun2 :: (a -> b -> c) -> (t -> a) -> (t -> b) -> (t -> c)
arg1 arg2 arg3

Composing two error-raising functions in Haskell

The problem I have been given says this:
In a similar way to mapMaybe, define
the function:
composeMaybe :: (a->Maybe b) -> (b -> Maybe c) -> (a-> Maybe c)
which composes two error-raising functions.
The type Maybe a and the function mapMaybe are coded like this:
data Maybe a = Nothing | Just a
mapMaybe g Nothing = Nothing
mapMaybe g (Just x) = Just (g x)
I tried using composition like this:
composeMaybe f g = f.g
But it does not compile.
Could anyone point me in the right direction?
The tool you are looking for already exists. There are two Kleisli composition operators in Control.Monad.
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
When m = Maybe, the implementation of composeMaybe becomes apparent:
composeMaybe = (>=>)
Looking at the definition of (>=>),
f >=> g = \x -> f x >>= g
which you can inline if you want to think about it in your own terms as
composeMaybe f g x = f x >>= g
or which could be written in do-sugar as:
composeMaybe f g x = do
y <- f x
g y
In general, I'd just stick to using (>=>), which has nice theoretical reasons for existing, because it provides the cleanest way to state the monad laws.
First of all: if anything it should be g.f, not f.g because you want a function which takes the same argument as f and gives the same return value as g. However that doesn't work because the return type of f does not equal the argument type of g (the return type of f has a Maybe in it and the argument type of g does not).
So what you need to do is: Define a function which takes a Maybe b as an argument. If that argument is Nothing, it should return Nothing. If the argument is Just b, it should return g b. composeMaybe should return the composition of the function with f.
Here is an excellent tutorial about Haskell monads (and especially the Maybe monad, which is used in the first examples).
composeMaybe :: (a -> Maybe b)
-> (b -> Maybe c)
-> (a -> Maybe c)
composeMaybe f g = \x ->
Since g takes an argument of type b, but f produces a value of type Maybe b, you have to pattern match on the result of f x if you want to pass that result to g.
case f x of
Nothing -> ...
Just y -> ...
A very similar function already exists — the monadic bind operator, >>=. Its type (for the Maybe monad) is Maybe a -> (a -> Maybe b) -> Maybe b, and it's used like this:
Just 100 >>= \n -> Just (show n) -- gives Just "100"
It's not exactly the same as your composeMaybe function, which takes a function returning a Maybe instead of a direct Maybe value for its first argument. But you can write your composeMaybe function very simply with this operator — it's almost as simple as the definition of the normal compose function, (.) f g x = f (g x).
Notice how close the types of composeMaybe's arguments are to what the monadic bind operator wants for its latter argument:
ghci> :t (>>=)
(>>=) :: (Monad m) => m a -> (a -> m b) -> m b
The order of f and g is backward for composition, so how about a better name?
thenMaybe :: (a -> Maybe b) -> (b -> Maybe c) -> (a -> Maybe c)
thenMaybe f g = (>>= g) . (>>= f) . return
Given the following definitions
times3 x = Just $ x * 3
saferecip x
| x == 0 = Nothing
| otherwise = Just $ 1 / x
one can, for example,
ghci> saferecip `thenMaybe` times3 $ 4
Just 0.75
ghci> saferecip `thenMaybe` times3 $ 8
Just 0.375
ghci> saferecip `thenMaybe` times3 $ 0
Nothing
ghci> times3 `thenMaybe` saferecip $ 0
Nothing
ghci> times3 `thenMaybe` saferecip $ 1
Just 0.3333333333333333