Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine functions to a function which returns a tuple

Is there a function in the Haskell standard library which takes two functions and returns a function which will return the results of both these functions in a tuple, something like this:

(><) :: (a -> b) -> (a -> c) -> a -> (b, c)
f >< g = \a -> (f a, g a)

So that:

((+2) >< (+3)) 10 == (12,13)
((:[1,2,3]) >< (*2)) 5 == ([5,1,2,3],10)
like image 294
foxterfox Avatar asked May 22 '16 19:05

foxterfox


People also ask

How do you return a tuple from a function?

Practical Data Science using Python Any object, even a tuple, can be returned by a Python function. Create the tuple object within the function body, assign it to a variable, and then use the keyword "return" to return the tuple to the function's caller.

Can function return tuple give example?

In each case, a function (which can only return a single value), can create a single tuple holding multiple elements. For example, we could write a function that returns both the area and the circumference of a circle of radius r. This workspace is provided for your convenience.

How do you return multiple things from a function in Python?

In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.

How can I return multiple values from a function?

If we want the function to return multiple values of same data types, we could return the pointer to array of that data types. We can also make the function return multiple values by using the arguments of the function.


2 Answers

&&& from Control.Arrow, has signature:

(&&&) :: Control.Arrow.Arrow a => a b c -> a b c' -> a b (c, c')

which is more generic than what you describe, but as shown here, when applied to functions, it resolves to:

(b -> c) -> (b -> c') -> (b -> (c, c'))

and it does what you describe:

\> import Control.Arrow ((&&&))

\> (+2) &&& (+3) $ 10
(12,13)

\> (:[1,2,3]) &&& (*2) $ 5 
([5,1,2,3],10)
like image 131
behzad.nouri Avatar answered Oct 16 '22 14:10

behzad.nouri


Use the Applicative instance for functions:

ghci> :t liftA2 (,)
liftA2 (,) :: Applicative f => f a -> f b -> f (a, b)

To make the signature more concrete, we specialize f to a function using TypeApplications (GHC >= 8):

ghci> :set -XTypeApplications
ghci> :t liftA2 @((->) _) (,)
liftA2 @((->)_) (,) :: (t -> a) -> (t -> b) -> t -> (a, b)
like image 6
danidiaz Avatar answered Oct 16 '22 12:10

danidiaz