@@ -118,6 +118,7 @@ import Prelude
118118import Control.Alt ((<|>))
119119import Control.Alternative (class Alternative )
120120import Control.Lazy (class Lazy , defer )
121+ import Control.Monad.Eff (foreachE )
121122import Control.Monad.Rec.Class (class MonadRec , Step (..), tailRecM2 )
122123import Control.Monad.ST as ST
123124import Data.Array.ST as STA
@@ -128,7 +129,7 @@ import Data.Foldable (foldl, foldr, foldMap, fold, intercalate, elem, notElem, f
128129import Data.Maybe (Maybe (..), maybe , isJust , fromJust )
129130import Data.Traversable (scanl , scanr ) as Exports
130131import Data.Traversable (sequence , traverse )
131- import Data.Tuple (Tuple (..))
132+ import Data.Tuple (Tuple (..), fst , snd , uncurry )
132133import Data.Unfoldable (class Unfoldable , unfoldr )
133134import Partial.Unsafe (unsafePartial )
134135import Unsafe.Coerce (unsafeCoerce )
@@ -876,8 +877,19 @@ groupBy op xs =
876877-- | nub [1, 2, 1, 3, 3] = [1, 2, 3]
877878-- | ```
878879-- |
879- nub :: forall a . Eq a => Array a -> Array a
880- nub = nubBy eq
880+ nub :: forall a . Ord a => Array a -> Array a
881+ nub arr = case head indexedAndSorted of
882+ Nothing -> []
883+ Just x -> map fst $ sortWith snd $ pureST do
884+ -- TODO: use NonEmptyArrays here to avoid partial functions
885+ result <- unsafeThaw $ singleton x
886+ foreachE indexedAndSorted \pair@(Tuple x' i) -> do
887+ lst <- fst <<< unsafePartial (fromJust <<< last) <$> unsafeFreeze result
888+ when (lst /= x') $ void $ pushSTArray result pair
889+ unsafeFreeze result
890+
891+ where
892+ indexedAndSorted = sort $ mapWithIndex (flip Tuple ) arr
881893
882894-- | Remove the duplicates from an array, where element equality is determined
883895-- | by the specified equivalence relation, creating a new array.
0 commit comments