|
235 | 235 | (set continue false)))
|
236 | 236 | _output }))
|
237 | 237 |
|
| 238 | +# @brief Partition a list in two, given a predicate |
| 239 | +# @param _L the list to work on |
| 240 | +# @param _f the predicate, accepting the value and its index |
| 241 | +# @details The original list is left unmodified. |
| 242 | +# =begin |
| 243 | +# (let a [1 2 3]) |
| 244 | +# (print (list:partition a (fun (c i) (= 0 (mod c 2))))) # [[2] [1 3]] |
| 245 | +# =end |
| 246 | +# @author https://github.com/rakista112 |
| 247 | +(let partition (fun (_L _f) { |
| 248 | + (mut _index 0) |
| 249 | + (mut _pass []) |
| 250 | + (mut _fail []) |
| 251 | + |
| 252 | + (while (< _index (len _L)) { |
| 253 | + (let _val (@ _L _index)) |
| 254 | + (if (_f _val _index) |
| 255 | + (append! _pass _val) |
| 256 | + (append! _fail _val)) |
| 257 | + (set _index (+ 1 _index)) }) |
| 258 | + |
| 259 | + [_pass _fail] })) |
| 260 | + |
238 | 261 | # @brief Unzip a list of [[a b] [c d]...] into [[a c ...] [b d ...]]
|
239 | 262 | # @param _L the list to work on
|
240 | 263 | # @details The original list is left unmodified.
|
|
426 | 449 | (if (not (empty? _current)) (append! _output _current))
|
427 | 450 |
|
428 | 451 | _output }))
|
| 452 | + |
| 453 | +# @brief Insert an element (or expand a list) at a given position inside a list |
| 454 | +# @details Original list is left unmodified |
| 455 | +# @param _L list to insert element(s) in |
| 456 | +# @param _index where to insert |
| 457 | +# @param _value value to insert |
| 458 | +# =begin |
| 459 | +# (let a [0]) |
| 460 | +# (print (list:insert a 1 4)) # [0 4] |
| 461 | +# (print (list:insert a 1 [1 2])) # [0 1 2] |
| 462 | +# (let b [0 9]) |
| 463 | +# (print (list:insert b 1 4)) # [0 4 9] |
| 464 | +# (print (list:insert b 1 [1 2])) # [0 1 2 9] |
| 465 | +# =end |
| 466 | +# @author https://github.com/SuperFola |
| 467 | +(let insert (fun (_L _index _value) { |
| 468 | + (let _size (len _L)) |
| 469 | + (assert (<= _index _size) "list:insert can not insert a value outside the list") |
| 470 | + |
| 471 | + (if (!= "List" (type _value)) |
| 472 | + (set _value [_value])) |
| 473 | + |
| 474 | + # insert at beginning |
| 475 | + (if (= 0 _index) |
| 476 | + (concat _value _L) |
| 477 | + # insert at the end |
| 478 | + (if (= _size _index) |
| 479 | + (concat _L _value) |
| 480 | + { |
| 481 | + # insert anywhere |
| 482 | + (let _parts (partition _L (fun (elem i &_index) (< i _index)))) |
| 483 | + (concat (head _parts) _value (@ _parts 1)) })) })) |
0 commit comments