Skip to content

Commit 5aa035a

Browse files
committed
Add cons
1 parent 9d32fec commit 5aa035a

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

docs/Data.Array.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,30 @@ for many use cases due to their poor asymptotics.
2020
This operator provides a safe way to read a value at a particular index
2121
from an array.
2222

23+
#### `cons`
24+
25+
``` purescript
26+
cons :: forall a. a -> [a] -> [a]
27+
```
28+
29+
Attaches an element to the front of an array, creating a new array.
30+
31+
```purescript
32+
cons 1 [2, 3, 4] = [1, 2, 3, 4]
33+
```
34+
35+
Note, the running time of this function is `O(n)`.
36+
37+
#### `(:)`
38+
39+
``` purescript
40+
(:) :: forall a. a -> [a] -> [a]
41+
```
42+
43+
An infix alias for `cons`.
44+
45+
Note, the running time of this function is `O(n)`.
46+
2347
#### `snoc`
2448

2549
``` purescript

src/Data/Array.purs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
module Data.Array
99
( (!!)
1010
, (..)
11+
, cons
12+
, (:)
1113
, snoc
1214
, singleton
1315
, head
@@ -72,6 +74,30 @@ infixl 8 !!
7274
(!!) xs n | n < zero || n >= length xs = Nothing
7375
| otherwise = Just (xs `unsafeIndex` toNumber n)
7476

77+
-- | Attaches an element to the front of an array, creating a new array.
78+
-- |
79+
-- | ```purescript
80+
-- | cons 1 [2, 3, 4] = [1, 2, 3, 4]
81+
-- | ```
82+
-- |
83+
-- | Note, the running time of this function is `O(n)`.
84+
foreign import cons
85+
"""
86+
function cons(e) {
87+
return function(l) {
88+
return [e].concat(l);
89+
};
90+
}
91+
""" :: forall a. a -> [a] -> [a]
92+
93+
infixr 6 :
94+
95+
-- | An infix alias for `cons`.
96+
-- |
97+
-- | Note, the running time of this function is `O(n)`.
98+
(:) :: forall a. a -> [a] -> [a]
99+
(:) = cons
100+
75101
-- | Append an element to the end of an array, creating a new array.
76102
foreign import snoc
77103
"""

0 commit comments

Comments
 (0)