Janet Notes and Examples

More Working With Data Structures

(def a [1 2 3])
(map some-fn a)

(map + [1 2 3] [4 5 6])        #=> @[5 7 9]
(map tuple [1 2] [3 4] [5 6])  #=> @[(1 3 5) (2 4 6)]
(zipcoll [:a :b :c] [1 2 3])   #=> @{:c 3 :a 1 :b 2}

# Use `;` to unpack values:
(def a [1 2 3]) # a tuple
(array ;a)      #=> @[1 2 3]

(filter even? (range 10))                      #=> @[0 2 4 6 8]
(interleave [:a :b :c] [1 2 3] ["x" "y" "z"])  #=> @[:a 1 x :b 2 y :c 3 z]
(interpose 100 (range 5))                      #=> @[0 100 1 100 2 100 3 100 4]

(frequencies [:w :w :x :w :y :y])              #=> @{:w 3 :x 1 :y 2}

(map |($ :type)
     [{:type "cat" :name "Fluffy"}
      {:type "dog" :name "Spot"}])
#=> @["cat" "dog"]

(map string/from-bytes "hello")
#=> @["h" "e" "l" "l" "o"]

# My own `cycle`.
(def a [44 55 66])

(defn cycle
  [a n]
  (let [ln (length a)]
    (seq [i :range [0 n]]
      (a (% i ln)))))

(pp (cycle a 8)) #=> @[44 55 66 44 55 66 44 55]

Sorting

Note that sort and sort-by sort in-place, whereas sorted and sorted-by return a new sorted array. Also note:

  • The function you pass as the 2nd arg to sort must be able to take two args and compare them returning a boolean (like >, >, etc.).
  • The function you pass to sort-by just takes one arg: the object you look at to figure out the value you want to sort on, which is what it then returns. Then < is used by default to sort by that.

For example:

(def a @[22 11 55 44])
(sort a)
(sort a >)   # instead of `<`

(defn f [x] (get-some-value-from x))
(sort-by f a)

See also the Janet docs on comparison operators.