Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would one want to use OneTuple?

Tags:

haskell

tuples

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?

like image 995
Tarrasch Avatar asked Sep 19 '11 17:09

Tarrasch


People also ask

How to define a tuple with one item in 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:

What are namedtuples and how do they work?

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:

Do I need to use new-object to create a tuple?

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.

Is a tuple faster than a list?

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.


2 Answers

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.

like image 145
hammar Avatar answered Sep 27 '22 20:09

hammar


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

like image 20
sclv Avatar answered Sep 27 '22 19:09

sclv