From 5aa035a777a491e32839ab5497b4f7a503c10c7a Mon Sep 17 00:00:00 2001 From: Harry Garrood Date: Thu, 30 Apr 2015 21:13:04 +0100 Subject: [PATCH] Add `cons` --- docs/Data.Array.md | 24 ++++++++++++++++++++++++ src/Data/Array.purs | 26 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/docs/Data.Array.md b/docs/Data.Array.md index 02690409..58f64c0b 100644 --- a/docs/Data.Array.md +++ b/docs/Data.Array.md @@ -20,6 +20,30 @@ for many use cases due to their poor asymptotics. This operator provides a safe way to read a value at a particular index from an array. +#### `cons` + +``` purescript +cons :: forall a. a -> [a] -> [a] +``` + +Attaches an element to the front of an array, creating a new array. + +```purescript +cons 1 [2, 3, 4] = [1, 2, 3, 4] +``` + +Note, the running time of this function is `O(n)`. + +#### `(:)` + +``` purescript +(:) :: forall a. a -> [a] -> [a] +``` + +An infix alias for `cons`. + +Note, the running time of this function is `O(n)`. + #### `snoc` ``` purescript diff --git a/src/Data/Array.purs b/src/Data/Array.purs index 5673e4ae..9e5b2cb2 100644 --- a/src/Data/Array.purs +++ b/src/Data/Array.purs @@ -8,6 +8,8 @@ module Data.Array ( (!!) , (..) + , cons + , (:) , snoc , singleton , head @@ -72,6 +74,30 @@ infixl 8 !! (!!) xs n | n < zero || n >= length xs = Nothing | otherwise = Just (xs `unsafeIndex` toNumber n) +-- | Attaches an element to the front of an array, creating a new array. +-- | +-- | ```purescript +-- | cons 1 [2, 3, 4] = [1, 2, 3, 4] +-- | ``` +-- | +-- | Note, the running time of this function is `O(n)`. +foreign import cons + """ + function cons(e) { + return function(l) { + return [e].concat(l); + }; + } + """ :: forall a. a -> [a] -> [a] + +infixr 6 : + +-- | An infix alias for `cons`. +-- | +-- | Note, the running time of this function is `O(n)`. +(:) :: forall a. a -> [a] -> [a] +(:) = cons + -- | Append an element to the end of an array, creating a new array. foreign import snoc """