You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
sugar/container.rkt

49 lines
2.3 KiB
Racket

#lang racket/base
(require "define.rkt")
11 years ago
(require "coerce.rkt" "len.rkt" racket/list)
11 years ago
(define (sliceable-container? x)
(ormap (λ(proc) (proc x)) (list list? string? symbol? vector?)))
11 years ago
(define (gettable-container? x)
(ormap (λ(proc) (proc x)) (list sliceable-container? hash?)))
11 years ago
(define+provide/contract (get container start [end #f])
((gettable-container? any/c) ((λ(i)(or (integer? i) (and (symbol? i) (equal? i 'end))))) . ->* . any/c)
11 years ago
(define result
(with-handlers ([exn:fail? (λ(exn) (error (format "Couldn't get item from ~a" container)))])
(let ([end (if (sliceable-container? container)
(cond
;; treat negative lengths as offset from end (Python style)
[(and (integer? end) (< end 0)) (+ (len container) end)]
;; 'end slices to the end
[(equal? end 'end) (len container)]
;; default to slice length of 1 (i.e, single-item retrieval)
[(equal? end #f) (add1 start)]
[else end])
end)])
(cond
[(list? container) (for/list ([i (range start end)]) (list-ref container i))]
[(vector? container) (for/vector ([i (range start end)]) (vector-ref container i))]
[(string? container) (substring container start end)]
[(symbol? container) (->symbol (get (->string container) start end))]
[(hash? container) (hash-ref container start)]
[else (error)]))))
;; don't return single-item results inside a list
(if (and (sliceable-container? container) (= (len result) 1))
(car (->list result))
result))
11 years ago
(define+provide/contract (in? item container)
11 years ago
(any/c any/c . -> . coerce/boolean?)
(cond
[(list? container) (member item container)] ; returns #f or sublist beginning with item
11 years ago
[(vector? container) (member item (vector->list container))] ; returns #f or sublist beginning with item
[(hash? container) (and (hash-has-key? container item) (get container item))] ; returns #f or hash value
11 years ago
[(string? container) (regexp-match (->string item) container)] ; returns #f or substring beginning with item
11 years ago
[(symbol? container) ((->string item) . in? . (->string container))] ; returns #f or subsymbol (?!) beginning with item
11 years ago
[else #f]))