Skip to content

Commit ccb9af9

Browse files
committed
Merge pull request #28 from hdgarrood/better-complexities
make `head` and `last` O(1), not O(n).
2 parents 78dc2f6 + af4364f commit ccb9af9

File tree

2 files changed

+3
-6
lines changed

2 files changed

+3
-6
lines changed

src/Data/Array.purs

+2-5
Original file line numberDiff line numberDiff line change
@@ -92,16 +92,13 @@ singleton a = [a]
9292

9393
-- | Get the first element in an array, or `Nothing` if the array is empty
9494
head :: forall a. [a] -> Maybe a
95-
head (x : _) = Just x
96-
head _ = Nothing
95+
head xs = xs !! 0
9796

9897
-- | Get the last element in an array, or `Nothing` if the array is empty
9998
-- |
10099
-- | Running time: `O(n)` where `n` is the length of the array
101100
last :: forall a. [a] -> Maybe a
102-
last (x : []) = Just x
103-
last (_ : xs) = last xs
104-
last _ = Nothing
101+
last xs = xs !! (length xs - 1)
105102

106103
-- | Get all but the first element of an array, creating a new array, or `Nothing` if the array is empty
107104
-- |

src/Data/Array/Unsafe.purs

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import qualified Data.Array as A
1111

1212
-- | Get the first element of a non-empty array.
1313
head :: forall a. [a] -> a
14-
head (x : _) = x
14+
head xs = unsafeIndex xs 0
1515

1616
-- | Get all but the first element of a non-empty array.
1717
tail :: forall a. [a] -> [a]

0 commit comments

Comments
 (0)