Title here
Summary here
We use range
to iterate over elements in a variety of built-in data structures. Let’s see how to use range
with some of the data structures we’ve learned.
(ns example.core
(:require [clojure.pprint :refer [pprint]]))
(defn -main []
;; Here we use `reduce` to sum the numbers in a vector.
(let [nums [2 3 4]
sum (reduce + nums)]
(println "sum:" sum))
;; `map-indexed` provides both the index and value for each entry.
(doseq [[i num] (map-indexed vector nums)]
(when (= num 3)
(println "index:" i)))
;; `range` on map iterates over key/value pairs.
(let [kvs {"a" "apple" "b" "banana"}]
(doseq [[k v] kvs]
(println (str k " -> " v))))
;; `keys` returns just the keys of a map.
(doseq [k (keys kvs)]
(println "key:" k))
;; `map` on string iterates over Unicode code points.
(doseq [[i c] (map-indexed vector "go")]
(println i (int c))))
;; To run the program, execute the following in your terminal:
;; $ clj -M -m example.core
To run the program, write the code in a file named core.clj
under a directory example
and run it using the clj
command.
$ clj -M -m example.core
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111
In this example, we’ve demonstrated how to sum elements in a vector, iterate with indices, handle maps and keys, and iterate over strings by their Unicode code points in Clojure. Now that we can work with these fundamental data structures and iteration methods, let’s learn more about the language.