Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Michiel de Mare inglua.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Rubylike slice for strings and lists

(slice "hello" 2 4) => "ll"
Comparable to: "hello"[2...4]

(slice "hello" 2 -1) => "ll"
Comparable to: "hello"[2...-1]

(slice "hello" '(2 2)) => "ll"
Comparable to: "hello"[2,2]

(slice "hello" 1) => "ello"
Comparable to: "hello"[2..-1]

(def slice (str x (o y))
  (if (atom x)
    (if 
      ; (slice "hello" 1) => "ello"
      (no y) 
        (subseq str x)
      ; (slice "hello" 2 -1) => "ll"
      (< y 0) 
        (subseq str x (+ (len str) y))
      ; (slice "hello" 2 4) => "ll"
      (subseq str x y))
    ; (slice "hello" '(2 2)) => "ll"
    (subseq str (car x) (+ (car x) (cadr x)))))
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS