Skip to content

Commit db10d08

Browse files
committed
Add nub/nubBy for NonEmptyList
1 parent 0871480 commit db10d08

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/Data/List/NonEmpty.purs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ module Data.List.NonEmpty
4646
, groupBy
4747
, groupAllBy
4848
, partition
49+
, nub
50+
, nubBy
4951
, nubEq
5052
, nubByEq
5153
, union
@@ -278,6 +280,12 @@ groupAllBy = wrappedOperation "groupAllBy" <<< L.groupAllBy
278280
partition :: forall a. (a -> Boolean) -> NonEmptyList a -> { yes :: L.List a, no :: L.List a }
279281
partition = lift <<< L.partition
280282

283+
nub :: forall a. Ord a => NonEmptyList a -> NonEmptyList a
284+
nub = wrappedOperation "nub" L.nub
285+
286+
nubBy :: forall a. (a -> a -> Ordering) -> NonEmptyList a -> NonEmptyList a
287+
nubBy = wrappedOperation "nubBy" <<< L.nubBy
288+
281289
nubEq :: forall a. Eq a => NonEmptyList a -> NonEmptyList a
282290
nubEq = wrappedOperation "nubEq" L.nubEq
283291

test/Test/Data/List/NonEmpty.purs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ module Test.Data.List.NonEmpty (testNonEmptyList) where
22

33
import Prelude
44

5+
import Data.Array as Array
56
import Data.Foldable (class Foldable, foldM, foldMap, foldl, length)
67
import Data.FoldableWithIndex (foldlWithIndex, foldrWithIndex, foldMapWithIndex)
8+
import Data.Function (on)
79
import Data.List as L
810
import Data.List.NonEmpty as NEL
911
import Data.Maybe (Maybe(..))
@@ -182,12 +184,19 @@ testNonEmptyList = do
182184
assert $ partitioned.yes == l [5, 3, 4]
183185
assert $ partitioned.no == l [1, 2]
184186

187+
log "nub should remove duplicate elements from the list, keeping the first occurence"
188+
assert $ NEL.nub (nel 1 [2, 2, 3, 4, 1]) == nel 1 [2, 3, 4]
189+
190+
log "nubBy should remove duplicate items from the list using a supplied predicate"
191+
let nubPred = compare `on` Array.length
192+
assert $ NEL.nubBy nubPred (nel [1] [[2],[3,4]]) == nel [1] [[3,4]]
193+
185194
log "nubEq should remove duplicate elements from the list, keeping the first occurence"
186195
assert $ NEL.nubEq (nel 1 [2, 2, 3, 4, 1]) == nel 1 [2, 3, 4]
187196

188197
log "nubByEq should remove duplicate items from the list using a supplied predicate"
189-
let nubPred = \x y -> if odd x then false else x == y
190-
assert $ NEL.nubByEq nubPred (nel 1 [2, 2, 3, 3, 4, 4, 1]) == nel 1 [2, 3, 3, 4, 1]
198+
let mod3eq = eq `on` \n -> mod n 3
199+
assert $ NEL.nubByEq mod3eq (nel 1 [3, 4, 5, 6]) == nel 1 [3, 5]
191200

192201
log "union should produce the union of two lists"
193202
assert $ NEL.union (nel 1 [2, 3]) (nel 2 [3, 4]) == nel 1 [2, 3, 4]

0 commit comments

Comments
 (0)