mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-24 10:01:38 +00:00
Clarify functional data structures.
Note that `set-add' is functional, clarify immutable hashes, add mutable hash examples to contrast.
This commit is contained in:
parent
5d952fb6da
commit
6af5c957d0
@ -147,10 +147,11 @@ my-pet ; => #<dog>
|
|||||||
|
|
||||||
;;; Sets
|
;;; Sets
|
||||||
|
|
||||||
;; create a set from a list
|
;; Create a set from a list
|
||||||
(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3)
|
(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3)
|
||||||
|
|
||||||
;; Add a member with `set-add'
|
;; Add a member with `set-add'
|
||||||
|
;; (Functional: returns the extended set rather than mutate the input)
|
||||||
(set-add (set 1 2 3) 4) ; => (set 1 2 3 4)
|
(set-add (set 1 2 3) 4) ; => (set 1 2 3 4)
|
||||||
|
|
||||||
;; Remove one with `set-remove'
|
;; Remove one with `set-remove'
|
||||||
@ -162,7 +163,7 @@ my-pet ; => #<dog>
|
|||||||
|
|
||||||
;;; Hashes
|
;;; Hashes
|
||||||
|
|
||||||
;; Create an immutable hash table (There are also mutables ones)
|
;; Create an immutable hash table (mutable example below)
|
||||||
(define m (hash 'a 1 'b 2 'c 3))
|
(define m (hash 'a 1 'b 2 'c 3))
|
||||||
|
|
||||||
;; Retrieve a value
|
;; Retrieve a value
|
||||||
@ -174,16 +175,26 @@ my-pet ; => #<dog>
|
|||||||
;; You can provide a default value for missing keys
|
;; You can provide a default value for missing keys
|
||||||
(hash-ref m 'd 0) ; => 0
|
(hash-ref m 'd 0) ; => 0
|
||||||
|
|
||||||
;; Use `hash-set' to extend a hash table
|
;; Use `hash-set' to extend an immutable hash table
|
||||||
|
;; (Returns the extended hash instdead of mutating it)
|
||||||
(define m2 (hash-set m 'd 4))
|
(define m2 (hash-set m 'd 4))
|
||||||
m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3))
|
m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3))
|
||||||
|
|
||||||
;; Remember, these hashes are immutable!
|
;; Remember, these hashes are immutable!
|
||||||
m ; => '#hash((b . 2) (a . 1) (c . 3))
|
m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
|
||||||
|
|
||||||
;; Use `hash-remove' to remove keys
|
;; Use `hash-remove' to remove keys (functional too)
|
||||||
(hash-remove m 'a) ; => '#hash((b . 2) (c . 3))
|
(hash-remove m 'a) ; => '#hash((b . 2) (c . 3))
|
||||||
|
|
||||||
|
;; Create an empty mutable hash table and manipulate it
|
||||||
|
(define m3 (make-hash))
|
||||||
|
(hash-set! m3 'a 1)
|
||||||
|
(hash-set! m3 'b 2)
|
||||||
|
(hash-set! m3 'c 3)
|
||||||
|
(hash-ref m3 'a) ; => 1
|
||||||
|
(hash-ref m3 'd 0) ; => 0
|
||||||
|
(hash-remove! m3 'a)
|
||||||
|
|
||||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||||
;; 3. Functions
|
;; 3. Functions
|
||||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||||
|
Loading…
Reference in New Issue
Block a user