File tree 3 files changed +47
-0
lines changed
3 files changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -131,6 +131,14 @@ exports.drop = function (n) {
131
131
} ;
132
132
} ;
133
133
134
+ exports . _slice = function ( b ) {
135
+ return function ( e ) {
136
+ return function ( s ) {
137
+ return s . slice ( b , e ) ;
138
+ } ;
139
+ } ;
140
+ } ;
141
+
134
142
exports . count = function ( p ) {
135
143
return function ( s ) {
136
144
var i = 0 ;
Original file line number Diff line number Diff line change @@ -26,6 +26,7 @@ module Data.String
26
26
, drop
27
27
, dropRight
28
28
, dropWhile
29
+ , slice
29
30
, stripPrefix
30
31
, stripSuffix
31
32
, count
@@ -172,6 +173,33 @@ takeWhile p s = take (count p s) s
172
173
dropWhile :: (Char -> Boolean ) -> String -> String
173
174
dropWhile p s = drop (count p s) s
174
175
176
+ -- | Returns the substring at indices `[begin, end)`.
177
+ -- | If either index is negative, it is normalised to `length s - index`,
178
+ -- | where `s` is the input string. `Nothing` is returned if either
179
+ -- | index is out of bounds or if `begin > end` after normalisation.
180
+ -- |
181
+ -- | ```purescript
182
+ -- | slice 0 0 "purescript" == Just ""
183
+ -- | slice 0 1 "purescript" == Just "p"
184
+ -- | slice 3 6 "purescript" == Just "esc"
185
+ -- | slice (-4) (-1) "purescript" == Just "rip"
186
+ -- | slice (-4) 3 "purescript" == Nothing
187
+ -- | ```
188
+ slice :: Int -> Int -> String -> Maybe String
189
+ slice b e s = if b' < 0 || b' >= l ||
190
+ e' < 0 || e' >= l ||
191
+ b' > e'
192
+ then Nothing
193
+ else Just (_slice b e s)
194
+ where
195
+ l = length s
196
+ norm x | x < 0 = l + x
197
+ | otherwise = x
198
+ b' = norm b
199
+ e' = norm e
200
+
201
+ foreign import _slice :: Int -> Int -> String -> String
202
+
175
203
-- | If the string starts with the given prefix, return the portion of the
176
204
-- | string left after removing it, as a Just value. Otherwise, return Nothing.
177
205
-- |
Original file line number Diff line number Diff line change @@ -206,3 +206,14 @@ testString = do
206
206
assert $ joinWith " " [] == " "
207
207
assert $ joinWith " " [" a" , " b" ] == " ab"
208
208
assert $ joinWith " --" [" a" , " b" , " c" ] == " a--b--c"
209
+
210
+ log " slice"
211
+ assert $ slice 0 0 " purescript" == Just " "
212
+ assert $ slice 0 1 " purescript" == Just " p"
213
+ assert $ slice 3 6 " purescript" == Just " esc"
214
+ assert $ slice (-4 ) (-1 ) " purescript" == Just " rip"
215
+ assert $ slice (-4 ) 3 " purescript" == Nothing -- b' > e'
216
+ assert $ slice 1000 3 " purescript" == Nothing -- b' > e' (subsumes b > l)
217
+ assert $ slice 2 (-15 ) " purescript" == Nothing -- e' < 0
218
+ assert $ slice (-15 ) 9 " purescript" == Nothing -- b' < 0
219
+ assert $ slice 3 1000 " purescript" == Nothing -- e > l
You can’t perform that action at this time.
0 commit comments