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)
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.
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.
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.
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.
&&&
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With