Title here
Summary here
Our first program will demonstrate iterating over elements in a variety of built-in data structures using for
. Let’s see how to use iteration with some of the data structures we’ve already learned.
#lang racket
(define (sum-list lst)
(define sum 0)
(for ([num lst])
(set! sum (+ sum num)))
(displayln (format "sum: ~a" sum)))
(define nums '(2 3 4))
(sum-list nums)
(for ([i nums]
[num (in-indexed nums)])
(when (= (cdr num) 3)
(displayln (format "index: ~a" (car num)))))
(define kvs (hash "a" "apple" "b" "banana"))
(for ([(k v) (in-hash kvs)])
(displayln (format "~a -> ~a" k v)))
(for ([k (in-hash-keys kvs)])
(displayln (format "key: ~a" k)))
(for ([p (in-string "go")])
(displayln (format "~a ~a" (char-index p) (char->integer (char-value p)))))
To run the program, save the code in a file named range-over-built-in-types.rkt
and then use the Racket interpreter to execute it.
$ racket range-over-built-in-types.rkt
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111
We’ve seen how to iterate over lists, hash tables, and strings in Racket. Now, let’s explore more about the language.