Skip to content

Commit 948a5da

Browse files
committed
use Ord for nub
O(n*logn)
1 parent 32a1a20 commit 948a5da

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/Data/Array.purs

Lines changed: 16 additions & 4 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 (Eff)
120121
import Control.Monad.Rec.Class (class MonadRec, Step(..), tailRecM2)
121-
import Control.Monad.ST (pureST)
122-
import Data.Array.ST (unsafeFreeze, emptySTArray, pokeSTArray, pushSTArray, modifySTArray, withArray)
122+
import Control.Monad.ST (ST, pureST)
123+
import Data.Array.ST (STArray, 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+
result <- unsafeThaw $ singleton x
882+
unsafeFreeze =<< foldRecM assimilate result sorted
883+
where
884+
sorted = sort arr
885+
886+
assimilate :: forall h. STArray h a -> a -> Eff (st :: ST h) (STArray h a)
887+
assimilate acc x = do
888+
lst <- unsafePartial (fromJust <<< last) <$> unsafeFreeze acc
889+
if lst == x then pure acc else pushSTArray acc x *> pure acc
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)