In Python and Ruby (and others as well, I'm sure). you can prefix an enumerable with *
("splat") to use it as an argument list. For instance, in Python:
>>> def foo(a,b): return a + b
>>> foo(1,2)
3
>>> tup = (1,2)
>>> foo(*tup)
3
Is there something similar in Haskell? I assume it wouldn't work on lists due to their arbitrary length, but I feel that with tuples it ought to work. Here's an example of what I'd like:
ghci> let f a b = a + b
ghci> :t f
f :: Num a => a -> a -> a
ghci> f 1 2
3
ghci> let tuple = (1,2)
I'm looking for an operator (or function) that allows me to do:
ghci> f `op` tuple
3
I have seen (<*>)
being called "splat", but it doesn't seem to be referring to the same thing as splat in other languages. I tried it anyway:
ghci> import Control.Applicative
ghci> f <*> tuple
<interactive>:1:7:
Couldn't match expected type `b0 -> b0'
with actual type `(Integer, Integer)'
In the second argument of `(<*>)', namely `tuple'
In the expression: f <*> tuple
In an equation for `it': it = f <*> tuple
The double splat operator came out back in Ruby 2.0. It’s pretty similar to the original splat with one difference: it can be used for hashes! Here’s an example for the most basic use of a double splat. I hope you can see that the possibilities are pretty endless with using these two together.
But the main idea is that whenever you don’t want to specify the number of arguments you have, you would use a splat operator. The simplest example would be something like this:
The main thing to keep in mind is that you use splats as a parameter in a method when you are unsure of how many arguments that method will be using. Lastly, I made a little function that shows how you can filter out any argument that is not a key value pair using both a single splat and double splat.
Yes, you can apply functions to tuples, using the tuple package. Check out, in particular, the uncurryN function, which handles up to 32-tuples:
Prelude Data.Tuple.Curry> (+) `uncurryN` (1, 2)
3
The uncurry function turns a function on two arguments into a function on a tuple. Lists would not work in general because of their requirement for homogeneity.
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