From 273fa8606b662dbec5b3b0b2fd0d3dfd648e00ab Mon Sep 17 00:00:00 2001 From: Geoffrey Liu Date: Sun, 26 Jun 2016 21:21:13 +0800 Subject: [racket/en] Add more details about Racket (#2278) * Add let* and letrec reference * More elaboration on structs * Add code about predefined car, cdr functions * Mention explicit typing, int to real conversion --- racket.html.markdown | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'racket.html.markdown') diff --git a/racket.html.markdown b/racket.html.markdown index 0fe3f030..96dcaf25 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -114,18 +114,42 @@ some-var ; => 5 "Alice" me) ; => "Bob" +;; let* is like let, but allows you to use previous bindings in creating later bindings +(let* ([x 1] + [y (+ x 1)]) + (* x y)) + +;; finally, letrec allows you to define recursive and mutually recursive functions +(letrec ([is-even? (lambda (n) + (or (zero? n) + (is-odd? (sub1 n))))] + [is-odd? (lambda (n) + (and (not (zero? n)) + (is-even? (sub1 n))))]) + (is-odd? 11)) + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 3. Structs and Collections ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Structs +; By default, structs are immutable (struct dog (name breed age)) (define my-pet (dog "lassie" "collie" 5)) my-pet ; => # +; returns whether the variable was constructed with the dog constructor (dog? my-pet) ; => #t +; accesses the name field of the variable constructed with the dog constructor (dog-name my-pet) ; => "lassie" +; You can explicitly declare a struct to be mutable with the #:mutable option +(struct rgba-color (red green blue alpha) #:mutable) +(define burgundy + (rgba-color 144 0 32 1.0)) +(set-color-green! burgundy 10) +(color-green burgundy) ; => 10 + ;;; Pairs (immutable) ;; `cons' constructs pairs, `car' and `cdr' extract the first ;; and second elements @@ -143,6 +167,16 @@ my-pet ; => # ;; and a quote can also be used for a literal list value '(1 2 3) ; => '(1 2 3) +;; Racket has predefined functions on top of car and cdr, to extract parts of a list +(cadr (list 1 2 3)) ; => 2 +(car (cdr (list 1 2 3))) ; => 2 + +(cddr (list 1 2 3)) ; => '(3) +(cdr (cdr (list 1 2 3))) ; => '(3) + +(caddr (list 1 2 3)) ; => 3 +(car (cdr (cdr (list 1 2 3)))) ; => 3 + ;; Can still use `cons' to add an item to the beginning of a list (cons 4 '(1 2 3)) ; => '(4 1 2 3) -- cgit v1.2.3