view 6-Clojure/loop_recur.clj @ 93:39084e2b8744

Add a function for word-aware text wrapping Potentially hugely inefficient because we iterate through the string character by character, but then splitting it first and iterating over words still needs to iterate over the string to know where to split.
author IBBoard <dev@ibboard.co.uk>
date Tue, 18 Jun 2019 21:05:00 +0100
parents a83309cdf5d3
children
line wrap: on
line source

; Define a function that takes a single parameter (which needs to be a list-like thing)
(defn size [_vec]
    ; Loop over _list with starting value of our parameter and _size with starting value of 0
    (loop [_list _vec, _size 0]
        ; Code to execute is just an "if" block
        (if (empty? _list)
            ; if our list is empty, return the size
            _size
            ; else call loop's body again (the "if" block) but this time pass in
            ; the tail of the list and the incremented size counter 
            (recur (rest _list) (inc _size)))))

(println (size [1 2 3 5 7 9]))
(println (size (list 1 2 3)))
(println (size #{}))
(println (size #{1}))