Skip to content

Commit b23e53e

Browse files
committed
use Ord for nub
addresses purescript#91 O(n*logn)
1 parent 32a1a20 commit b23e53e

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/Data/Array.purs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,10 @@ import Prelude
117117
import Control.Alt ((<|>))
118118
import Control.Alternative (class Alternative)
119119
import Control.Lazy (class Lazy, defer)
120+
import Control.Monad.Eff (foreachE)
120121
import Control.Monad.Rec.Class (class MonadRec, Step(..), tailRecM2)
121122
import Control.Monad.ST (pureST)
122-
import Data.Array.ST (unsafeFreeze, emptySTArray, pokeSTArray, pushSTArray, modifySTArray, withArray)
123+
import Data.Array.ST (unsafeFreeze, unsafeThaw, emptySTArray, pokeSTArray, pushSTArray, modifySTArray, withArray)
123124
import Data.Array.ST.Iterator (iterator, iterate, pushWhile)
124125
import Data.Foldable (class Foldable, foldl, foldr, traverse_)
125126
import Data.Foldable (foldl, foldr, foldMap, fold, intercalate, elem, notElem, find, findMap, any, all) as Exports
@@ -873,8 +874,19 @@ groupBy op xs =
873874
-- | nub [1, 2, 1, 3, 3] = [1, 2, 3]
874875
-- | ```
875876
-- |
876-
nub :: forall a. Eq a => Array a -> Array a
877-
nub = nubBy eq
877+
nub :: forall a. Ord a => Array a -> Array a
878+
nub arr = case head sorted of
879+
Nothing -> []
880+
Just x -> pureST do
881+
-- TODO: use NonEmptyArrays here to avoid partial functions
882+
result <- unsafeThaw $ singleton x
883+
foreachE sorted \x' -> do
884+
lst <- unsafePartial (fromJust <<< last) <$> unsafeFreeze result
885+
when (lst /= x') $ void $ pushSTArray result x'
886+
unsafeFreeze result
887+
888+
where
889+
sorted = sort arr
878890

879891
-- | Remove the duplicates from an array, where element equality is determined
880892
-- | by the specified equivalence relation, creating a new array.

0 commit comments

Comments
 (0)