Returning a function in Haskell - haskell

In Haskell, is it possible to return a function from within a function? I tried searching on Hoogle for:
(a -> b) -> a -> b
but couldn't find any functions that could achieve this.

Yes, you can, and it's so common and deeply ingrained in the language that you don't even notice it!
For instance, when you write
mean :: Double -> Double -> Double
mean a b = (a + b) / 2
What you're really doing is, you define a function
mean :: Double -> EndoDouble
mean a = meanA
where meanA b = (a + b) / 2
where the type of meanA,
type EndoDouble = Double -> Double
happens to be a function type.
So, any "multi-parameter function" in Haskell really is a single-parameter function that returns a function! The concept is called Currying, you might have heard about it.

Treating functions as first-class citizens is one of the advantages of Haskell and doesn't require any special syntax.
For example if you want to have a function which will double the result of given function you can write:
doubleFunction f = (\x -> 2 * (f x))
When given a function f, doubleFunction is equal to a function which multiplies (f x) by 2. You can write it using function composition:
doubleFunction f = (* 2) . f
or even shorter:
doubleFunction = ((* 2) .)
doubleFunction is of type:
doubleFunction :: (Num a) => (a -> b) -> a -> b

Yes, you can: functions are values in Haskell, so it can be as simple as
functionIdentity :: (a -> b) -> a -> b
functionIdentity f = f
...which is just a specialised identity function.
You may also "explicitly" return a function by using a lambda if you wish, like const:
const x = \_ -> x

Related

Haskell difference between function composition and bind

I can't understand the difference between Dot (function composition) and bind (>>=) .
If I understand, these two ways take the previous result of a function for a new function.
So what is the difference ?
They are pretty different. Let's look at their signatures:
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(>>=) :: (Monad m) => m a -> (a -> m b) -> m b
As you said, the function composition is just a way to pass a result of one function as an argument to another one like this:
f = g . h
is equivalent to
f x = g (h x)
You can think about is as some kind of a "conveyor", where your value goes through several processing steps.
But (>>=) is quite different. It is related to such context as monad which is something like some value in some context (it's highly recommended to read the previous link if you aren't familiar with it).
So let x be some value in a context. Our context will be nullability (Maybe monad), and the value is 2. So, x = Just 2. We could, for example, get it as a result of a lookup from some associative container (such operation might fail, that's the reason why it is Maybe Int, but not Int).
Now we want to pass our x to some arithmetic function f that accepts just Int and may fail, so its signature looks like:
f :: Int -> Maybe Int
We can't just pass our value because of type mismatch. We could unpack x and handle some cases with if, but we could do that in almost all other languages. In haskell, we can use (>>=):
x >>= f
This allows as to chain the effects:
if x is Nothing, then the result is Nothing immediately
else x is unpacked and passed to f
This is a generalization of the operator ?., that you could see in some languages:
x = a?.func1()?.func2();
which checks for null at each "step" and stops immediately if hits null or returns the value in case of success. In haskell it looks like:
x = a >>= func1 >>= func2
However, bind with monads is a much more powerful concept, allowing you, for example, to emulate stateful computations in a language without mutability like haskell.
(>>=) is a form of function application.
(>>=) :: Monad m => m a -> (a -> m b) -> m b
flip ($) :: a -> (a -> b) -> b
It takes a value, but "extracts" part of it in order to apply the given function. Chaining two functions, like x >>= f >>= g requires the argument type of g to be different from (but at the same type similar to) the return type of f, unlike composition, which requires the types to match exactly.
Composed with return, it
really is just function application, but restricted to certain kinds of functions.
flip ($) :: a -> (a -> b) -> b
(>>=) . return :: Monad m => a -> (a -> m b) -> m b
(.) is more like (<=<) (from Control.Monad).
(.) :: (b -> c) -> (a -> b) -> a -> c
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
But again, instead of simply passing the result of one function to another, it first "extracts" a value before doing application.

Is a function with a functional argument curried?

From https://stackoverflow.com/a/57020455/156458
In Haskell, it happens that everything is curried; all functions take just one argument (even uncurried functions in Haskell take a tuple, which is, strictly speaking, a single argument -- you might want to play with the curry and uncurry functions to see how that works).
I am not sure if that is true, but assume so.
If a function takes another function as an argument, is it curried or uncurried in a similar sense as a function taking a tuple or list argument being uncurried? (A pair tuple type is type1 x type2 and can be type1^2, while a function type is type2^{type1}, so I find them similar)
If uncurried, how can I convert such a function to a curried function?
If a function takes another function as an argument, is it curried or uncurried?
It takes just a function, so a single parameter, and hence it is curried. The fact that that parameter is a function is irrelevant.
Such a function is for example map. map has type:
map :: (a -> b) -> ([a] -> [b])
It thus takes a single parameter, a function (of type a -> b), and then returns a function [a] -> [b] that will map a list of as to a list of bs by applying that function.
So map show :: Show a => [a] -> [String] is the result of such function application, and this is again a function.
Yes, the quote is correct. All the talk about "curried" and "uncurried" functions is imprecise jargon.
Haskell is a curried language. Functions in Haskell always have exponential types. If an argument is a tuple, it doesn't matter, it is still just one value (which happens to be a tuple).
The concepts are approximated when we treat an (a,b) -> c Haskell function as the c a * b one. But it's just a mental gymnastics that we do.
What's actually curried or not, are programming languages. For instance, in Lisp,
(lambda (a b) c)
actually has the type c a * b and to turn it into the (c b)a function we need to put it through some transformations.
There actually is no (\a b -> c) lambdas in Haskell, only (\ a -> (\ b -> c)) nested lambdas(*) . When we write (\a b -> c) in Haskell, it is just a syntactical shortcut for (\ a -> (\ b -> c)). It is impossible to have actual (\a b -> c) lambda function in Haskell, though it is approximated by having (\(a,b) -> c) lambda function.
Where you really see the meaning of all this, if when you implement your own language with lambda functions.
Faced with a ((lambda (a b) c) x y z) function call, the real issue is how to pair-up the function's parameters and the values supplied.
Haskell converts it into ((let a=x in (let b=y in c)) z), but Lisp actually pairs up the parameters list (a b) with the list of values (x y z) and reports the length mismatch.
But, being the uncurried language that it is, Lisp is able to have the various twists and tweaks here, like optional arguments, default arguments, named arguments, etc., pairing up the parameters and the values in various different ways -- unlike Haskell, which always pairs up one parameter with one supplied value at a time.
(*) and with another crucial distinction: the a and b in Haskell's (\ a -> (\ b -> c)) are not variables, but patterns. They are not just assigned the values, like in Lisp -- they are matched up with them.
The truth I can see at least, is almost every value in haskell can be seen as a function with, and every function just take one parameter at the time. Let see an example (With Int as example, to be more clear):
f :: Int -> Int -> Int -> Int
f x y z = x + y + z
f can be seen as a function that takes a Int and returns a function
Int -> (Int -> Int)
:t (f 2)
(f 2) :: Int -> Int -> Int
:t (f 2 3)
(f 2 3) :: Int -> Int
(f 2 3) can be seen as a function that takes a Int and returns an Int
finally
:t (f 2 3 4)
(f 2 3 4) :: Int
An example with higher order functions:
h :: (Int -> Int -> Int) -> Int -> Int -> Int
h fn x y = fn x y
A little more complex but just the same idea:
:t (h f)
(h f) :: Int -> Int -> Int -> Int
(h f) is a function, expecting an Int , and returning (Int -> Int -> Int -> Int)
but... wait, was not it expecting to return a function? it should be so
(h f) :: Int -> Int -> (Int -> Int)
well, point made. let's continue
:t (h f 2)
(h f 2) :: Int -> Int -> Int
(h f 2) is a function expecting a Int and returning a function (Int -> Int)
and finally
:t (h f 2 3)
(h f 2 3) :: Int -> Int
(h f 2 3) indeed is a function, expecting a Int, returning an Int
(h f 2 3) 4 == 7
I think the conclusion here is, every function is curried in Haskell.

Haskell: How to recognize a curried function?

Given the following two functions:
minCur a = (\b -> if a > b then b else a)
minCur a b = if a > b then b else a
Asking for the type results for both the same:
minCur :: Ord p => p -> p -> p
How does the User of the function know if he is dealing with a curried function? Does it even matter?
Edit:
Is this currying?
minCur (a,b) = if a > b then b else a
It does not matter, since every function that takes more than one argument is a curried function. In Haskell, every function takes a single parameter and returns a single value (a -> b -> c is the same as a -> (b -> c)).
There shouldn't be a reason for the user to care whether the function is curried or not.
The two function definitions you provided are considered to be the same function. The user shouldn't need to care beyond what the behavior of minCur is and what type it has.
In the case of the version with the tuple, it has a different type. So
min (a, b) = if a > b then b else a
min :: Ord p => (p, p) -> p
And the types (a, a) -> a and a -> a -> a are incompatible. You cannot curry the function with the tuple because it only has one parameter anyway and does not return a function type.
In the libraries, we have a function curry which transforms
f :: (A,B) -> C
f (a,b) = ...
into g = curry f, defined as
g :: A -> B -> C
g a b = ...
We also have the inverse transformation, called uncurry which maps g back into f = uncurry g.
Sometimes, functions like g are called "curried" and functions like f are called "uncurried". This way of speaking is a bit informal since we should instead say, more properly, "g is the curried form of f" and "f is the uncurried form of g".
There is no perfect distinction between "curried" and "uncurried" functions on ther own. For instance, h :: (A,B) -> C -> D can be seen as the currying of h1 :: ((A,B),C) -> D or the uncurrying of h2 :: A -> B -> C -> D, so it would be both curried and uncurred at the same time.
Often, though, we say that a function is curried or not depending on whether it takes a tuple as a single argument or its components as separate arguments. Again, this is a bit informal.
When choosing which style to follow, in Haskell we prefer the curried form since it is easier to apply partially.

Haskell (.) for function with multiple operands

The (.) operator has the signature:
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g x = f $ g x
This looks a bit similar to the composition function in primitive recursive functions with one g.
I'm not interested in extending the number of g-functions, but (a number of) functions that apply the (.) function on a function g with multiple operands. In other words something like:
(..) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(..) f g x y = f $ g x y
A search on Hoogle doesn't result in any function. Is there a package that can handle this with an arbitrary number of operands?
To answer-ify my comments:
Multi-argument function composition operators are very easy to define, and luckily someone has done this for you already. The composition package has a nice set of operators for you to use to compose functions in this manner. I also find that instead of using haskell.org's hoogle engine, fpcomplete's version searches through more packages making it easier to find what I'm looking for.

Is there a built-in Haskell equivalent for C++'s std::bind2nd?

What I'm missing is the ability to partially apply the second argument of a function rather than the first. This is especially useful when I want to pass the function to something like map, but without having to write a lambda for it each time.
I wrote my own function for this (definition below, just in case there indeed isn't any built-in function for this and anyone else was curious), but I would really like to know if there already exists something in the Prelude for this idiom as I prefer to reuse rather than reinvent.
Here is my definition and a trivial example:
bind2nd :: (a -> b -> c) -> b -> a -> c
bind2nd f b = \a -> f a b
foo :: Int -> Bool -> String
foo n b | b = show n
| otherwise = "blabla"
alwaysN :: Int -> String
alwaysN = bind2nd foo True
It's called flip.
Example:
Prelude> flip (-) 2 3
1
For future reference, it could have been found by simply searching Hoogle for the type signature in your question, namely (a -> b -> c) -> b -> a -> c. :-)

Resources