Reputation: 101
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.
Upvotes: 1
Views: 1345
Reputation: 363
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
Upvotes: 3
Reputation: 120751
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.
Upvotes: 6
Reputation: 1975
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
Upvotes: 3