Proposal: add uncons (and unsnoc) to Data.List

wren romano winterkoninkje at gmail.com
Sun Jul 20 03:01:28 UTC 2014


On Sat, Jul 19, 2014 at 6:47 PM, David Feuer <david.feuer at gmail.com> wrote:
> Alexander Berntsen indicates that he has a branch all ready to go. Henning
> Thienemann seems to prefer the term viewL. Alexander says that Edward Kmett
> says that uncons/unsnoc is the more common term. Personally, I find uncons
> and unsnoc to be more intuitive names. Details:
>
> uncons :: [a] -> Maybe (a, [a])
> uncons [] = Nothing
> uncons (a:as) = Just (a,as)

+1 for uncons.

Yes, uncons is a view, but I see no benefit in naming the function
after that fact— given that "uncons" is the standard/popular name, and
that we don't typically name any other views "viewFoo".


> -- Henning's implementation of "viewR", renamed, looks like
>
> unsnoc :: [a] -> Maybe ([a], a)
> unsnoc = foldr (\x -> Just . forcePair . maybe ([],x) (mapFst (x:))) Nothing
>
> I wonder if it would be possible to tease that apart a bit to get the maybe
> out of the loop, which I think might be prettier. The really tricky part of
> unsnoc is making it lazy enough—messing around with it a bit suggested that
> it's very easy to mess up the pair lifting. The tough rule seems to be this
> mouthful, if I'm not mistaken:
>
> unsnoc (xs ++ (y : _|_)) = Just (xs ++ _|_, _|_)

unsnoc :: [a] -> Maybe ([a],a)
unsnoc []     = Nothing
unsnoc (x:xs) = Just $ go x xs
    where
    go x []     = ([], x)
    go x (y:ys) = let ~(zs,z) = go y ys in (x:zs, z)

I've never had any reason to use it. But since the implementation is
tricky, I'm +1 if other folks want it.

-- 
Live well,
~wren


More information about the Libraries mailing list