Skip to content
35 changes: 35 additions & 0 deletions core/core/Array.hs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ module Array (
set,
push,
append,
dropLast,
dropRight,
slice,

-- * LinkedLists
Expand Down Expand Up @@ -575,6 +577,39 @@ indexed :: Array a -> Array (Int, a)
indexed (Array vector) = Array (Data.Vector.indexed vector)


-- | Remove the last element of an array.
-- Returns the original array when it is empty.
--
-- >>> dropLast (fromLinkedList [1,2,3] :: Array Int)
-- Array [1,2]
-- >>> dropLast (fromLinkedList [] :: Array Int)
-- Array []
dropLast :: Array element -> Array element
dropLast arr =
if isEmpty arr
then arr
else take (length arr - 1) arr


-- | Remove the last @n@ elements from an array.
-- When @n <= 0@, returns the original array.
-- When @n >= length@, returns an empty array.
--
-- >>> dropRight 2 (fromLinkedList [1,2,3] :: Array Int)
-- Array [1]
-- >>> dropRight 0 (fromLinkedList [1,2,3] :: Array Int)
-- Array [1,2,3]
-- >>> dropRight 5 (fromLinkedList [1,2,3] :: Array Int)
-- Array []
dropRight :: Int -> Array element -> Array element
dropRight n arr = do
let len = length arr
keep = max 0 (len - n)
if keep == len
then arr
else take keep arr


-- | Zip two arrays into a new array of tuples.
-- >>> (fromLinkedList [1,2,3] :: Array Int) |> zip (fromLinkedList [4,5,6] :: Array Int)
-- Array [(1,4),(2,5),(3,6)]
Expand Down
27 changes: 27 additions & 0 deletions core/test/ArraySpec.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{-# OPTIONS_GHC -Wno-unused-imports #-}

module ArraySpec where

import Array qualified
import Test
Comment thread
NickSeagull marked this conversation as resolved.

spec :: Spec Unit
spec = do
describe "Array" do
describe "dropLast" do
it "removes the final element" \_ -> do
Array.fromLinkedList [1, 2, 3] |> Array.dropLast |> shouldBe (Array.fromLinkedList [1, 2])

it "returns the same empty array" \_ -> do
Array.empty |> Array.dropLast |> shouldBe (Array.empty :: Array.Array Int)

describe "dropRight" do
it "drops the last n elements" \_ -> do
Array.fromLinkedList [1, 2, 3, 4] |> Array.dropRight 2 |> shouldBe (Array.fromLinkedList [1, 2])

it "returns the original array when n is zero" \_ -> do
Array.fromLinkedList [1, 2, 3] |> Array.dropRight 0 |> shouldBe (Array.fromLinkedList [1, 2, 3])

it "returns an empty array when n is at least the length" \_ -> do
Array.fromLinkedList [1, 2, 3] |> Array.dropRight 3 |> shouldBe (Array.empty :: Array.Array Int)
Array.fromLinkedList [1, 2, 3] |> Array.dropRight 5 |> shouldBe (Array.empty :: Array.Array Int)
Loading