Search code examples
functional-programmingclojure

Clojure - launch 'for i in range(0, x)' (begin ques)


all I want to do is increment 'i' as list elements go, but it seems that sequence starts from '1' as incrementing go first (?)

(fn [lst]
(doseq [i (for [i (range (count lst))] (inc i))]
        (println i)

))

All I want to get is '0' for 1-range list, but it returns '1'. I tried to 'for [i 0 (range (count lst))', but it errors. Ty.


Solution

  • Use doseq if you want to perform side effects only - without collecting the result. Use for loop if you want to collect the result.

    Somehow you weirdly use both, doseq an for.

    I think, what you want is this:

    (defn count-list [lst]
      (doseq [i (range (count lst))]
        (println i)))
    

    In Python, there is enumerate() to loop over lists and at the same time to have an index (position of the element in the list).

    l = ['a', 'b', 'c']
    for i, el in enumerate(l):
       print(f"index: {i} value: {el}")
    

    In Clojure you could do this with map-indexed:

    (def l ["a" "b" "c"])
    
    (map-indexed (fn [i el] [i el]) l)
    ;; => ([0 "a"] [1 "b"] [2 "c"])
    

    Just I want to say is: In Python, looping over a list using its index is quite C-ish - and not Pythonic. Also in Clojure, you rarely need the index. Because you could do:

    (def l ["a" "b" "c"])
    
    (for [el l]
      ; do something with `el` here
      ; and return the value which should be collected!
      el)
    

    similar to Python's list-comprehensions:

    [el for el in l]