functional programming - Clojure manually find nth element in a sequence -


i newbie clojure (and functional programming matter) , trying basic problems. trying find nth element in sequence without recursion.

so like

(my-nth '(1 2 3 4) 2) => 3 

i had hard time looping through list , returning when found nth element. tried bunch of different ways , code ended is

(defn sdsu-nth  [input-list n]  (loop [cnt n tmp-list input-list]     (if (zero? cnt)        (first tmp-list)        (recur (dec cnt) (pop tmp-list))))) 

this gives me exception says "cant pop empty list"

i dont need code, if point me in right direction help!

you using function pop, has different behavior different data structures.

user> (pop '(0 1 2 3 4)) (1 2 3 4) user> (pop [0 1 2 3 4]) [0 1 2 3] user> (pop (map identity '(0 1 2 3 4))) classcastexception clojure.lang.lazyseq cannot cast clojure.lang.ipersistentstack  clojure.lang.rt.pop (rt.java:640) 

furthermore, mixing calls pop calls first. if iterating, use peek/pop or first/rest pairs, mixing 2 can lead unexpected results. first / rest lowest common denominator, if want generalize on various sequential types, use those, , coerce sequence work if can.

user> (first "hello") \h user> (first #{0 1 2 3 4}) 0 user> (first {:a 0 :b 1 :c 2}) [:c 2] 

with function, replacing pop rest, expected results:

user> (defn sdsu-nth         [input-list n]         (loop [cnt n tmp-list input-list]               (if (zero? cnt)                   (first tmp-list)                 (recur (dec cnt) (rest tmp-list)))))  #'user/sdsu-nth user> (sdsu-nth (map identity '(0 1 2 3 4)) 2) 2 user> (sdsu-nth [0 1 2 3 4] 2) 2 user> (sdsu-nth '(0 1 2 3 4) 2) 2 user> (sdsu-nth "01234" 2) \2 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -