Skip to content

Instantly share code, notes, and snippets.

@scmu
Last active April 26, 2018 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scmu/900cc6b30972d2b55bf9cfc8803d8c3c to your computer and use it in GitHub Desktop.
Save scmu/900cc6b30972d2b55bf9cfc8803d8c3c to your computer and use it in GitHub Desktop.
One-Liner nub
import Data.Ord
import Data.List
nubSimple :: [Int] -> [Int]
nubSimple = map head . group . sort
nubStable :: [Int] -> [Int]
nubStable = map fst . sortBy (comparing snd). map head .
groupBy ((. fst).(==).fst) . sort . flip zip [0..]
@jc99kuo
Copy link

jc99kuo commented Apr 26, 2018

Question: Whether the spec of nub requires to maintain the order of elements?
As in module Data.List
nub [1,2,3,48,6,4,3,2] ==> [1,2,3,48,6,4]

By the way, nub :: Eq a => [a] -> [a], not "Ord a"
so sort :: Ord a => [a] -> [a] may not work on type a.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment