Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I take a slice of a list (A sublist) in scheme?

Tags:

lisp

scheme

Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ?

EDIT:

Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land.

like image 532
troelskn Avatar asked Sep 20 '08 13:09

troelskn


People also ask

How to slice list of list in Python?

With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.

Does slicing create a new list?

In short, slicing is a flexible tool to build new lists out of an existing list. Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges. Also, any new data structure can add its support as well.

How do you append to a sublist in Python?

Add items to a Nested list. To add new values to the end of the nested list, use append() method. When you want to insert an item at a specific position in a nested list, use insert() method. You can merge one list into another by using extend() method.


1 Answers

Strangely, slice is not provided with SRFI-1 but you can make it shorter by using SRFI-1's take and drop:

(define (slice l offset n)
  (take (drop l offset) n))

I thought that one of the extensions I've used with Scheme, like the PLT Scheme library or Swindle, would have this built-in, but it doesn't seem to be the case. It's not even defined in the new R6RS libraries.

like image 65
Nathan Shively-Sanders Avatar answered Sep 19 '22 08:09

Nathan Shively-Sanders