diff --git a/src/Data/Array.purs b/src/Data/Array.purs index a510f0f3..662c2e09 100644 --- a/src/Data/Array.purs +++ b/src/Data/Array.purs @@ -68,6 +68,7 @@ module Data.Array , filterM , mapMaybe , catMaybes + , mapWithIndex , sort , sortBy @@ -411,6 +412,14 @@ mapMaybe f = concatMap (maybe [] singleton <<< f) catMaybes :: forall a. Array (Maybe a) -> Array a catMaybes = mapMaybe id +-- | Apply a function to each element in an array, supplying a generated +-- | zero-based index integer along with the element, creating an array +-- | with the new elements. +mapWithIndex :: forall a b. (Int -> a -> b) -> Array a -> Array b +mapWithIndex f xs = + zipWith f (range 0 (length xs - 1)) xs + + -------------------------------------------------------------------------------- -- Sorting --------------------------------------------------------------------- -------------------------------------------------------------------------------- diff --git a/test/Test/Data/Array.purs b/test/Test/Data/Array.purs index 75085164..f3981214 100644 --- a/test/Test/Data/Array.purs +++ b/test/Test/Data/Array.purs @@ -5,7 +5,7 @@ import Prelude import Control.Monad.Eff (Eff) import Control.Monad.Eff.Console (log, CONSOLE) -import Data.Array (range, foldM, unzip, zip, zipWithA, zipWith, intersectBy, intersect, (\\), deleteBy, delete, unionBy, union, nubBy, nub, groupBy, group', group, span, dropWhile, drop, takeWhile, take, sortBy, sort, catMaybes, mapMaybe, filterM, filter, concat, concatMap, reverse, alterAt, modifyAt, updateAt, deleteAt, insertAt, findLastIndex, findIndex, elemLastIndex, elemIndex, (!!), uncons, init, tail, last, head, insertBy, insert, snoc, (:), length, null, singleton, fromFoldable) +import Data.Array (range, foldM, unzip, zip, zipWithA, zipWith, intersectBy, intersect, (\\), deleteBy, delete, unionBy, union, nubBy, nub, groupBy, group', group, span, dropWhile, drop, takeWhile, take, sortBy, sort, catMaybes, mapMaybe, mapWithIndex, filterM, filter, concat, concatMap, reverse, alterAt, modifyAt, updateAt, deleteAt, insertAt, findLastIndex, findIndex, elemLastIndex, elemIndex, (!!), uncons, init, tail, last, head, insertBy, insert, snoc, (:), length, null, singleton, fromFoldable) import Data.Foldable (for_, foldMapDefaultR, class Foldable, all) import Data.Maybe (Maybe(..), isNothing, fromJust) import Data.Tuple (Tuple(..)) @@ -201,6 +201,9 @@ testArray = do log "catMaybe should take an array of Maybe values and throw out Nothings" assert $ catMaybes [Nothing, Just 2, Nothing, Just 4] == [2, 4] + log "mapWithIndex applies a function with an index for every element" + assert $ mapWithIndex (\i x -> x - i) [9,8,7,6,5] == [9,7,5,3,1] + log "sort should reorder a list into ascending order based on the result of compare" assert $ sort [1, 3, 2, 5, 6, 4] == [1, 2, 3, 4, 5, 6]