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

Rubylike slice for strings and lists (See related posts)

(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)))))

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts