Proposal: Add singleton function to Data.List module

Matt parsonsmatt at gmail.com
Tue Aug 13 22:25:58 UTC 2019


The point is to create a monomorphic variant that avoids the problems with
the polymorphic `pure` and would be consistent with the other
container-types. A polymorphic `singleton` would be useful, but - in the
same way that `Map.fromLIst` and `Set.fromList` are (usefully!) monomorphic
despite equivalent `IsList` methods, we'd still want to have a concrete
`List.singleton :: a -> [a]`.

I see a lot of "Why isn't `pure` good enough here?", so I'd like to
reiterate that `pure` has issues:

- It's not immediately+syntactically obvious what's being created.
List.singleton is unambiguous to read.
- Polymorphism can cause unintended changes to behavior if GHC infers a
different type than you expect. Consider `length (1,2)` confusion, `fmap
(+1) (Left 1)` - while these have an obviously correct instance, it can
still be confusing and yield potentially incorrect results.
- Monomorphic functions can often be very useful to inform GHC about a
specific type you want to fix and allow the rest of inference to work
around. Typed-holes provide *much* better information when you have
concrete types rather than constrained polymorphic types.
- Finally, monomorphic functions can be used to prevent ambiguous type
errors in the presence of OverloadedLists and OverloadedStrings, especially
when every other method in the chain is written on Foldable or similar
constraints.

Matt Parsons


On Tue, Aug 13, 2019 at 4:13 PM Herbert Valerio Riedel <hvriedel at gmail.com>
wrote:

> >  There is a concept here: create a container containing exactly one
> value. As Tikhon indicates, this is a different concept from pure.
>
> Fwiw, if you actually want a possibly meaningful/lawful reification of
> the very specific "create any container containing exactly one item"
> concept then an obvious approach would be to base it on the existing
> (IMO under-appreciated) 'IsList' abstraction; in other words basically
> something like
>
>     singleton :: IsList l => Item l -> l
>     singleton = fromListN 1 . (:[])
>
> which could either be a method of `IsList` (with the default impl
> above and an obvious lawful relationship to `fromList`/`toList`) or
> just be a top-level binding exported from "GHC.List" and/or "GHC.Exts"
> (which aren't governed by the Haskell Library Report and thus have a
> lower barrier to entry).
> _______________________________________________
> Libraries mailing list
> Libraries at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/libraries
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/libraries/attachments/20190813/3141d3a1/attachment.html>


More information about the Libraries mailing list