I just stumbled upon the package OneTuple on hackage. I want to know it's purpose, I'm certain the author didn't create it just for the fun of it. So when can this be useful? It's quite clear what it does, but not when one would use it.
So, anyone know any cool examples when you can benefit from this? Or perhaps show the mathematical beauty behind it?
The main thing to look out for is if you need to define a tuple with a single item in it, you need to include a trailing comma, otherwise you’ll just end up with the thing you tried to define inside the tuple, but it won’t actually be a tuple. Like so:
The short version is, namedtuples give you the ability to predefine attributes, or fields, that are “accessible by attribute lookup as well as being indexable and iterable.” So what does that mean? Here’s an example:
I do not need to use New-Object —I can simply call the appropriate Create method and create the appropriate tuple. Here is an example of how to create a singleton (or a 1-tuple) and access the data stored in the tuple.
I created a list and a tuple, each containing the numbers 0 through 999, and looped through them 100k times. With both, it took just under 1.5 seconds. If anything, the list was faster, though not significantly so. If speed is the only reason you have for using a tuple, it’s probably not worth it.
It's nearly the same as the Identity
monad, which is commonly used as the base of a monad transformer stack, except that since OneTuple
uses data
instead of newtype
it has an additional bottom value.
It's interesting because it's in a sense the most trivial example of most of the type classes it implements. I don't see much of a practical use for it, though.
Suppose you have a (slightly silly) typeclass that operates on tuples. You have an instance for (a,a)
, an instance for (a,a,a)
. You want an instance for a single value as well. But you can't just make an instance for a
because that would overlap with everything else! You can, however, make an instance for OneTuple a
.
Now that typeclass is a bit useless, but its easy to imagine a typeclass almost like it but more useful. In fact, this is precisely the use of Only
in bos' mysql library: http://hackage.haskell.org/packages/archive/mysql-simple/0.2.0.2/doc/html/Database-MySQL-Simple-QueryResults.html
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