Difference between revisions of "Composing functions with multiple values"

From HaskellWiki
Jump to navigation Jump to search
(initial version)
 
m (→‎Answer: spacing (this wiki's parser is really weird))
 
(One intermediate revision by one other user not shown)
Line 25: Line 25:
 
You can't convert a pair to something that fits
 
You can't convert a pair to something that fits
 
a function that accepts two arguments in curried form.
 
a function that accepts two arguments in curried form.
But you can convert the curried function
+
But you can convert the curried function to one that accepts pairs using the standard function <hask>uncurry</hask>!
to one that accepts pairs using the standard function <hask>uncurry</hask>!
 
   
 
It is
 
It is
Line 51: Line 50:
   
 
[[Category:FAQ]]
 
[[Category:FAQ]]
  +
[[Category:Idioms]]

Latest revision as of 23:09, 26 January 2016

Question

I see a certain imbalance between multiple function arguments and multiple function values. On the one hand functions with multiple arguments are often in curried form, like

(++) :: [a] -> [a] -> [a]

which allows for partial application. On the other hand, functions cannot emit values in a compatible way, and thus must return pairs instead. Example:

partition :: (a -> Bool) -> [a] -> ([a], [a])

How can I convert the result of partition such that it meets the needs of (++)?

Answer

You can't convert a pair to something that fits a function that accepts two arguments in curried form. But you can convert the curried function to one that accepts pairs using the standard function uncurry!

It is

uncurry (++) :: ([a], [a]) -> [a]

and consequently

uncurry (++) . partition p :: [a] -> [a]

is what you are after.

In fact, there is no imbalance. Functions always accept exactly one input and emit exactly one output. You can always choose tuples as both input and output. Using tuples as input is close to the way other languages handle multiple inputs. If you choose the curried form you do that because of partial application. In this case you should also think intensively about how to order the parameters in order to make partial application useful.