user310291
user310291

Reputation: 38190

What's the equivalent of Python's list[3:7] in REBOL or Red?

With Rebol pick I can only get one element:

list: [1 2 3 4 5 6 7 8 9]

pick list 3

In python one can get a whole sub-list with

list[3:7]

Upvotes: 2

Views: 144

Answers (2)

Graham Chiu
Graham Chiu

Reputation: 4886

>> list: [1 2 3 4 5 6 7 8 9]
== [1 2 3 4 5 6 7 8 9]
>> copy/part skip list 2 5
== [3 4 5 6 7]

So, you can skip to the right location in the list, and then copy as many consecutive members as you need.

If you want an equivalent function, you can write your own.

Upvotes: 3

  • AT can seek a position at a list.
  • COPY will copy from a position to the end of list, by default
  • the /PART refinement of COPY lets you add a limit to copying

Passing an integer to /PART assumes how many things you want to copy:

>> list: [1 2 3 4 5 6 7 8 9]

>> copy/part (at list 3) 5
== [3 4 5 6 7]

If you provide a series position to be the end, then it will copy up to that point, so you'd have to be past it if your range means to be inclusive.

>> copy/part (at list 3) (next at list 7)
== [3 4 5 6 7]

There have been some proposals for range dialects, I can't find any offhand. Simple code to give an idea:

range: func [list [series!] spec [block!] /local start end] [
    if not parse spec [
        set start integer! '.. set end integer!
    ][
        do make error! "Bad range spec, expected e.g. [3 .. 7]"
    ]
    copy/part (at list start) (next at list end) 
]

>> list: [1 2 3 4 5 6 7 8 9]

>> range list [3 .. 7]
== [3 4 5 6 7]

Upvotes: 6

Related Questions