Op woensdag 30 april 2014 09:58:26 UTC+2 schreef James Reeves: > > On 30 April 2014 07:49, Roelof Wobben <rwo...@hotmail.com <javascript:>>wrote: >> >> >> Op woensdag 30 april 2014 08:21:40 UTC+2 schreef James Reeves: >> >>> >>> 1. How do you find the last element of a seq with exactly one element? >>> >> >> the last and the first element are the same >> > > Right. So to formalise it: > > (defn last* [coll] > (first coll)) > > I'm using "last*" as the name so that it doesn't conflict with the > function "last" in clojure.core. > > > 2. How do you find out whether a seq has one element, or more than one >>> element? >>> >> >> Look at the length of the seq >> > > Unlike vectors, seqs are simple structures and don't know their own length. > > You can count seqs, but this involves iterating through every element in > turn. If all you want to do is find out whether there is more than one > element, there's a much simpler and more efficient way. > > > Yep, if there is only 1 item is a list (rest coll) is nil.
> In code, this would be: > > (defn last* [coll] > (if (more-than-one-element? coll) > (first (rest coll)) > (first coll))) > > The "more-than-one-element?" to be replaced with the answer to question 2, > of course. > > Can you think of a way of making this function recursive to work with any > number of elements? > I think I can but I have to try some things but untested it looks like this (defn last* [coll] (if (nil? (rest coll) (first coll))) > (last* (rest coll)) > Now I wonder how I can make it work if I want to find lets say the 5th value of a array of any number of elements Then rest is never nil. So at first glance if I do not know the length it cannnot be done recursive. I have to do it in a for loop. > - James > -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.